Home > Enterprise >  Execute MainActivity method inside recyclerView
Execute MainActivity method inside recyclerView

Time:11-05

I have a Layout as an image and a recyclerView below the image, I want the image to change when the user clicks on one of the elements in the list.

I tried to do it this way, but it didn't work:

Method to change the image that is in MainActivity

`

    public void setImagem (){

    runOnUiThread(new Runnable() {

        public void run() {

            imageView.setImageResource(R.drawable.cascatinha);

        }
    });

}

` onClick method inside the recyclerView

`

        holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MainActivity mainActivity = new MainActivity();
            mainActivity.setImagem();


        }
    });

`

When I click on one of the elements, the app closes and this error message appears:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference

CodePudding user response:

runOnUiThread does not give you access to any underlying view, it just runs on a thread that is responsible for rendering UI.

The idea behind it is correct though. You need to have some way to reference an element from the activity.

Create some interface with a callback function and create an instance in the activity.

interface OnItemClickListener {
    void onItemClick(/* Here have an argument that you want to pass from RecyclerView*/);
}

Activity implementation:

private OnItemClickListener mListener = new OnItemClickListener () {
    @Override
    public void onItemClick(String message) { // e.g. message
        //setImage();
    }
};

And just pass it in the constructor of the adapter and store it.

new *****Adapter(..., listener)

class ****Adapter {

    private OnItemClickListener mListener;

And just invoke it in the onClickListener that you set there:

holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        listener.onItemClick("message");
    }
});
  • Related