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?
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:
getApplicationContext()
MyActivity.this
Your code should be mostly unchanged:
myViewModel.getAllDataVM().observe(getApplicationContext(), new Observer<List<MyRoomEntity>>() {
@Override
public void onChanged(@Nullable List<MyRoomEntity> myRoomEntities) {
//.....
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM