Android: “Cannot Resolve symbol 'addValueEventListener'” in Firebase

允我心安 提交于 2019-12-24 01:53:32

问题


I've tried importing a variety of Firebase packages to stop this error from occurring, but it still persists. I'm trying to do something along the lines of:

   firebase.addValueEventListener(new ValueEventListener() {

but I'm consistently getting the error:

Cannot Resolve symbol 'addValueEventListener'

despite the fact I have ValueEventListener imported. (It might be important to note that ValueEventListener is displayed in the IDE as an unused import, even though I'm clearly attempting to use it)


回答1:


Make sure that you are instantiating and adding the method inside a method such as OnStart(){} or the constructor of the class you are working in. If it is not it will behave similar to how you describe.

An Example of this issue :

public class ReadFromFireBase(){

 private DatabaseReference mDatabase;

public ReadFromFireBase(){
}

ValueEventListener postListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // Get Post object and use the values to update the UI
        Post post = dataSnapshot.getValue(Post.class);
        // ...
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        // ...
    }
};
mDataBase.addValueEventListener(postListener);




} 

This will not work and throw errors similar to what you are getting, it is an easy mistake to make given the way the listener is structured

The proper way would be something such as :

public class ReadFromFireBase(){

 private DatabaseReference mDatabase;
 private ValueEventListener postListener;


   public ReadFromFireBase(){
   postListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // Get Post object and use the values to update the UI
        Post post = dataSnapshot.getValue(Post.class);
        // ...
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        // ...
    }
};
mDataBase.addValueEventListener(postListener);
}






} 


来源:https://stackoverflow.com/questions/43750662/android-cannot-resolve-symbol-addvalueeventlistener-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!