0

i have a relative layout and an imageView i want to set the relative layout background image through the imageView image ressource , this is the code :

 ImageView iv = new ImageView(null) ;
   Picasso.get().load("http://10.0.2.2:3000/uploads/"+imgtrip+".png").into(iv); 
   viewHolder.rltvLayout.setBackground(iv.getDrawable);

i am getting this error :

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference

in this line :


  ImageView iv = new ImageView(null) ;
CoderTn
  • 985
  • 2
  • 22
  • 49

1 Answers1

0

The ImageView constructor requires a Context parameter.

If this code is in your activity, pass this, or getActivity() from a fragment, or pass the activity into the adapter's constructor if it is a listview/recyclerview adapter and use that in the view holder, etc.

In your case, in your adapter,

class MyAdapter extends ListAdapter {
    private Context mContext;

    public MyAdapter(Context context) {
        mContext = context;
    }

    // ...

    // in where you use ImageView
    {
        ImageView iv = new ImageView(mContext);
        //...
    }

}

And in where you create a new MyAdapter, usually in your activity or fragment, you have now something like MyAdapter adapter = new MyAdapter(), instead change that to MyAdapter adapter = new MyAdapter(this) if it is in your activity (since Activity is a type of Context) or MyAdapter adapter = new MyAdapter(getContext()) if it is in your fragment.

See this if you don't know the difference of Activity and Fragment.

See the inheritance hierarchy here if you don't know the relationship between Activity and Context.

Daniel
  • 400
  • 1
  • 2
  • 12