从Firestore下载数据很晚

时间:2019-01-03 16:40:01

标签: java android firebase google-cloud-firestore

我想用一个片段包裹一个array。可拆分阵列取决于Firestore数据检索。我的意思是数组的元素来自Firestore。但是从Firestore检索数据的时间太晚了,下一行代码正在执行,并且空数组也正在打包。使下几行做什么,直到从Firestore检索数据?

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {



private static final String MAPVIEW_BUNDLE_KEY = "MapViewBundleKey";
private static final int PERMISSIONS_REQUEST_ENABLE_GPS = 9001;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 9002;
private static final String TAG = "MainActivity";
private static final int ERROR_DIALOG_REQUEST = 9003;
private boolean mLocationPermissionGranted = false;

private List<User>mUserList=new ArrayList<>();
private ArrayList<UserLocation>mUserLocations=new ArrayList<>();

private FusedLocationProviderClient mFusedLocationProviderClient;
FirebaseFirestore mDb;

private GoogleMap mGoogleMap;
private UserLocation mUserPosition=null;
private LatLngBounds latLngBoundary;

private ClusterManager mClusterManager;
private MyClusterManagerRenderer mClusterManagerRenderer;
private ArrayList<ClusterMarker> mClusterMarkers=new ArrayList<>();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mDb = FirebaseFirestore.getInstance();

    initUser();//in this method the data retrieving is implemented

    if (findViewById(R.id.fragment_container) != null) {
        if (savedInstanceState != null) {
            return;
        }            
        MapFragment mapFragment = new MapFragment();
        Bundle bundle=new Bundle();
        bundle.putParcelableArrayList(getString(R.string.userlocations_array),  mUserLocations);
        mapFragment.setArguments(bundle);


        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, mapFragment).commit();
    }

}

private void initUser() {
    User user=new User();
    user.setEmail("nobeld@gmail.com");
    user.setResponse("ok");
    user.setUser("student");
    user.setUserId("5");
    user.setUserName("nobel");
    ((UserClient)(getApplicationContext())).setUser(user);
    mUserList.add(user);
    User user1=new User();
    user1.setEmail("rahuld@gmail.com");
    user1.setResponse("ok");
    user1.setUser("student");
    user1.setUserId("6");
    user1.setUserName("rahul");
    User user2=new User();
    user2.setEmail("milond@gmail.com");
    user2.setResponse("ok");
    user2.setUser("student");
    user2.setUserId("7");
    user2.setUserName("milon");
    mUserList.add(user1);
    mUserList.add(user2);
    for(User u: mUserList){
        getUserLocation(u);
        //firestore is implemented inside this method
        Log.d(TAG, "initUser: in user array");
    }



}

private void setCameraView(){
    if(mUserPosition!= null){
        Log.d(TAG, "setCameraView: user position got");
        double bottomboundary=mUserPosition.getGeo_point().getLatitude()-.05;
        double leftboundary = mUserPosition.getGeo_point().getLongitude()-.05;
        double upboundary = mUserPosition.getGeo_point().getLatitude()+.05;
        double rightboundary = mUserPosition.getGeo_point().getLongitude()+.05;
        latLngBoundary=new LatLngBounds(new LatLng(bottomboundary,leftboundary),
                new LatLng(upboundary,rightboundary));
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBoundary,0));

    }else {
        Log.d(TAG, "setCameraView: user position is null");
    }
}
private void getUserLocation(User user){
    Log.d(TAG, "getUserLocation: ");
    DocumentReference locationRef=mDb.collection(getString(R.string.collection_user_location_student))
            .document(user.getUserId());
    locationRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if(task.isSuccessful()){
                if(task.getResult().toObject(UserLocation.class)!= null){
                    Log.d(TAG, "Location onComplete: ");
                    UserLocation u=task.getResult().toObject(UserLocation.class);
                    mUserLocations.add(u);
                    //here adding the elements to array.

                }else {
                    Log.d(TAG, "onComplete: result is empty");
                }
            }
        }
    });

}

}

2 个答案:

答案 0 :(得分:2)

由于数据是异步行为,因此仅在onComplete()方法内可用,因此当您尝试将mUserLocations列表添加到Bundle对象时,数据还没有还没有完成从数据库的加载,这就是为什么无法访问(列表为空)的原因。快速解决此问题的方法是移动以下代码行:

Bundle bundle=new Bundle();
bundle.putParcelableArrayList(getString(R.string.userlocations_array),  mUserLocations);
mapFragment.setArguments(bundle);

在下面的代码行之后的onComplete()方法内部:

//here adding the elements to array.
  

做什么直到下一行才等待从Firestore中检索数据?

如果您想在该方法之外使用mUserLocations,建议您从 post 中查看anwser的最后一部分,在其中我已经解释了如何使用使用自定义回调完成。您也可以查看此 video 以获得更好的理解。

答案 1 :(得分:1)

这些功能不会立即完成。相反,它们通过您提供的OnCompleteListener回调interface返回结果。这是因为您的设备需要花费一些时间才能与服务器进行通信,服务器需要认证和处理您的请求并返回您请求的数据。

如果您需要在继续之前收集所有数据,建议您重新编写查询以一次查询所有必需数据(即一次不查询单个请求),然后在回调完成后执行后续步骤已执行(即在回调的末尾调用方法),或者通过在UI线程上执行请求并使用synchronization来阻止任务执行,直到完成为止。

无论哪种方式,您发出的请求都是异步,并且您的代码在等待响应的同时尝试执行一些有用的操作。这就是为什么它继续前进的原因。