所以我有一个MainActivity,当它的onCreate方法运行时,应该从Firebase调出一组数据,但是,列表每次都返回0。
值得注意的是,当我转到另一个活动(暂停MainActivity),然后在返回MainActivity时调用onResume()时,该方法运行良好,返回了所需的结果.....我怀疑这与活动寿命有关循环,但似乎无法固定下来。
将该方法放在onCreate(),onStart()和onResume()上,结果相同,结果为0,并且在导航到另一个活动并返回时得到相同的行为,这给了我数据。
有什么想法吗?
我的onResume()方法:
@Override
protected void onResume() {
super.onResume();
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION);
}
else if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_EXTERNAL);
}
try{
mFusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
FirebaseAuth auth = FirebaseAuth.getInstance();
double lattitude = location.getLatitude();
double longitude = location.getLongitude();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("GeoFire");
GeoFire geofire = new GeoFire(ref);
geofire.setLocation(auth.getUid(), new GeoLocation(lattitude, longitude), new GeoFire.CompletionListener() {
@Override
public void onComplete(String key, DatabaseError error) {
if (error != null) {
System.err.println("There was an error saving the location to GeoFire: " + error);
} else {
System.out.println("Location saved on server successfully!");
}
}
});
}
});}
catch (SecurityException e){
}
generateData();
}
mFusedLocationClient是类FusedLocationProvierClient的实例。可以找到文档here.
GenerateData方法:
userDb.orderByChild("aField").equalTo(constraint).limitToLast(50).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
getUserList(); // runs geolocation
//GENERATE LIST
for (DataSnapshot ds : dataSnapshot.getChildren()) {
try {
User tempUser = ds.getValue(User.class);
userList.add(tempUser);
setActive(userList);
}
Log.d("userListSize", String.valueOf(userList.size()));
} catch (IndexOutOfBoundsException e) {
Log.d("Index EXception", e.getMessage());
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});