Ad

What Is The Owner Parameter In The Live Data Observer When Put In An OnClickListener?

When clicking a button I want to make a query for my Room data. I have an observable on my data that I put in the OnClickListener. The observer works fine outside of the OnClickListener method, but inside of it, the owner parameter is a mismatch.

Android Studio asks for android.arch.lifecycle.LifeCycleOwner but says that it gets android.view.View.OnClickListener.

showAllButton.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        //The "this" parameter is underlined red

            myViewModel.getAllDataVM().observe(    this   , new Observer<List<MyRoomEntity>>() {
                @Override
                public void onChanged(@Nullable List<MyRoomEntity> myRoomEntities) {
                    //myAdapter.setList( myRoomEntities );

                    Log.d("TAG", "OBSERVED");
                    if(myRoomEntities != null) {
                        for(MyRoomEntity item: myRoomEntities) {
                            Log.d("TAG ROOM ", "" + item.toString());
                        }
                    }
                }
            } );
        }
    } );//End Button

this is underlined in red, which is the owner parameter. I have tried using context, application, etc, but nothing works. Maybe it's not possible to have an observer inside an OnClickListener, but what do I do then?

Ad

Answer

This is a common error that is easily fixable. The this keyword is currently referring to the View.OnClickListener which is not one of the arguments for .observe(). Hence, to fix this problem, you simply have to replace this with:

  1. getApplicationContext()
  2. MyActivity.this

Your code should be mostly unchanged:

 myViewModel.getAllDataVM().observe(getApplicationContext(), new Observer<List<MyRoomEntity>>() {
     @Override
     public void onChanged(@Nullable List<MyRoomEntity> myRoomEntities) {
         //.....
Ad
source: stackoverflow.com
Ad