问题
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