Issue
I have the following class:
public class MainActivity extends AppCompatActivity
And
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {return false;}
@Override
public boolean onQueryTextChange(String searchText) {
if (searchText.length() > 0) {
myLiveData.removeObservers(this);
}
return false;
}
});
To the removeObservers()
function I need to pass a LifecycleOwner
object. When using this line:
myLiveData.removeObservers(this);
Inside my activity, it works fine but inside the onQueryTextChange()
it fails. How to make this
point to the right class and get the corresponding LifecycleOwner
object?
Solution
This is not related to Android, but more related to Java and its working.
When you want to reference the outer Class inside an inner class you will use OuterClassName.this
. In Your case it will be MainActivity.this
public class MainActivity extends AppCompatActivity{
public void onCreate(){
myLiveData.removeObservers(this);
}
}
When working with inner class, the above code will change to this.
public class MainActivity extends AppCompatActivity{
public void onCreate(){
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
@Override
public boolean onQueryTextSubmit(String s) {return false;}
@Override
public boolean onQueryTextChange(String searchText) {
if (searchText.length() > 0) {
myLiveData.removeObservers(MainActivity.this);
}
return false;
}
});
}
}
Answered By - Saran Sankaran
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.