我有一些代码从Firebase获取数据,这些代码有效,但不知何故停止工作。ValueEventListener
中的所有内容都被跳过,因为它给了我一个错误:"没有这样的实例字段:"mDatabase"。我该如何解决这个问题?我试过重新启动安卓工作室和我的电脑,但它一直给我这个错误......
法典:
mDatabase = FirebaseDatabase.getInstance().getReference();
ValueEventListener dataListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Make list for ReisData objects
reisDataList = new ArrayList<ReisData>();
// Put objects from database into java object list
for (DataSnapshot ds : dataSnapshot.child("allData").getChildren()) {
data = ds.getValue(ReisData.class);
reisDataList.add(data);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting data failed, log a message
Log.w("Error:", databaseError.toException());
}
};
mDatabase.addValueEventListener(dataListener);
编辑:我想我可能已经找到了问题。在此代码下,我添加了一些代码来显示reisDataList
的内容,这似乎干扰了ValueEventListener
。有没有办法运行此代码而不会出现任何错误?
添加的代码:
MyTripsAdapter myTripsAdapter = new MyTripsAdapter(getContext(), reisDataList);
ListView listView = (ListView) view.findViewById(R.id.mijnReizenList);
listView.setAdapter(myTripsAdapter);*/
此代码可以帮助您解决问题。
公共类Map_Activity扩展了 AppCompatActivity {
private DatabaseReference databaseRefer;
private FirebaseDatabase mFirebaseInstance;
private ArrayList<Location> reisDataList = new ArrayList<>();
private MyTripsAdapter myTripsAdapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mFirebaseInstance = FirebaseDatabase.getInstance(); //getting instance of FireDatabase
//getting db reference from specific node, here you're not refering the node
databaseRefer = mFirebaseInstance.getReference("windfirm/future");
ListView listView = (ListView) view.findViewById(R.id.mijnReizenList);
databaseRefer.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// pendingCount is the count for dataSnapshot children
long[] pendingCount = { dataSnapshot.getChildrenCount() };
//parsing all the node list data from dataSnapshot
for (DataSnapshot child : dataSnapshot.getChildren()) {
String rightLocation = child.child("lat").getValue().toString();
String leftLocation = child.child("lon").getValue().toString();
String city = child.child("city").getValue().toString();
reisDataList.add(new Location(rightLocation, leftLocation, city)); //adding object to arraylist
// we loaded a child, check if we're done
pendingCount[0] = pendingCount[0] - 1;
if (pendingCount[0] == 0) {
myTripsAdapter = new MyTripsAdapter(getContext(), reisDataList);
listView.setAdapter(myTripsAdapter);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}