2

I have two pictures I would like to rotate as a background image on an android app in a fragment.

Right now one is statically in the .xml as

android:background="@drawable/background"

I am trying to initialize the two photos in my Fragment.java but I am getting null pointer errors.

private Drawable img1 =
ContextCompat.getDrawable(this.getContext(),R.drawable.background);

private Drawable img2 =
ContextCompat.getDrawable(this.getContext(),R.drawable.background2);

Does anyone have any suggestions why I am getting a null error here?

Thanks!

GIGAMOLE
  • 1,274
  • 1
  • 11
  • 17

2 Answers2

0

You probably want getActivity() rather than getContext(). getContext was added in API 23, and I think results in a NPE if called in prior versions.

cwbowron
  • 1,015
  • 6
  • 10
0

Call it in the onCreateView instead of assigning the value directly. it will resolve your issue.

private Drawable deleteIcon;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
deleteIcon= ContextCompat.getDrawable(getContext(),R.drawable.ic_delete_black_24dp);}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Asghar Nazir
  • 329
  • 5
  • 23