0

I have a custom view that is extended from RelativeLayout.

I wanted to try to make this custom view as a singleton.

I have this code:

private static CameraView sCameraView;
public static synchronized CameraView getInstance(Context context) {
    if (sCameraView == null) {
        sCameraView = new CameraView(context);
    }
    return sCameraView;
}

And tried to use this from a fragment as:

private CameraView mCameraView = CameraView.getInstance(getActivity().getApplicationContext());

mCameraView = (CameraView) mView.findViewById(R.id.camera_preview);

I'm getting a NullPointException from this code. Then also an InflateException when I switch things around a little bit.

How would I approach to access the static instance from the custom view and assign it to a variable? because doing this:

CameraView.getInstance(getActivity().getApplicationContext()) = (CameraView) mView.findViewById(R.id.camera_preview);

isn't allowed.

Any help will be very appreciated.

JWL
  • 63
  • 3
  • 12
  • 1
    "I wanted to try to make this custom view as a singleton" -- you will leak memory (making the singleton dangerous), and the view will not work in other activities (making the singleton useless). I strongly suggest that you come up with another plan. Beyond that, use LogCat to examine the Java stack trace associated with your crashes: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this If you do not understand a stack trace, edit your question and post it. – CommonsWare Jan 17 '17 at 18:40
  • Alright, Thanks for your answer #CommonsWare. I knew that singleton wasn't a good choice but I was experimenting about having a singleton view in android. – JWL Jan 17 '17 at 22:52

1 Answers1

-1

private static CameraView sCameraView; is a static reference, but it's not desirable. Read this

You should avoid declaring UI elements as static. Hope this solves your problem.

Mayank Bhatnagar
  • 2,120
  • 1
  • 12
  • 20