Android:如何使用Firebase正确获取数据?

时间:2018-06-04 12:54:59

标签: android firebase asynchronous google-cloud-firestore

我正在使用Firebase开发我的第一个Android应用程序,我喜欢它。我的问题是,我应该如何正确地从Firebase数据库中获取数据?我对获取数据有点困惑,然后使用该数据获取更多数据。

我基本上将'OnCompleteListeners'嵌套在另一个内部,这种模式让我感到不安。是否有更好,更正确的方式?

这是我目前的做法:

//This is a weather app, users can monitor different weather stations 

//We first get the weather stations that the current user owns:
// I used two collections in this approach, "ownership" permission is read only to the user
DocumentReference docRef = mDatabase.collection("ownership").document( mUser.getUid() );

docRef.get().addOnCompleteListener( new OnCompleteListener<DocumentSnapshot>() {

    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {

        if ( task.isSuccessful() ) {

            DocumentSnapshot document = task.getResult();
            if ( document.exists() ) {

                Map<String, Object> data = document.getData();
                if ( data != null && data.containsKey("stations") ) {

                    // data is an string array, here is my ugly solution:
                    stationIds = data.get("stations").toString().replaceAll("[\\[\\]]", "").split(",");

                    if ( stationIds.length != 0 ) {

                        for ( int i = 0; i < stationIds.length; i++ ) {

                            // Now that I have the stations IDs I can get its data:
                            // !! the collection "stations" have read and write permission
                            // THIS PATTERN SEEMS VERY REDUNDANT!
                            DocumentReference docRef = mDatabase.collection("stations").document(stationIds[i]);
                            docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                    if (task.isSuccessful()) {
                                        DocumentSnapshot document = task.getResult();
                                        if (document.exists()) {
                                            Map<String, Object> data = document.getData();
                                            Log.d(TAG, "Document Snapshot: " + document.getData());

                                            if ( data != null && data.containsKey("name") ) {
                                                LinearLayout ll_root = MainActivity.this.findViewById(R.id.ll_station_list);

                                                LinearLayout ll_new = new LinearLayout(MainActivity.this);
                                                ll_new.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                                                ll_new.setPadding(20,50,20,20);

                                                TextView tv_station_title = new TextView(MainActivity.this);
                                                tv_station_title.setText(data.get("name").toString());
                                                ll_new.addView( tv_station_title);
                                                ll_root.addView( ll_new );


                                                ll_new.setOnClickListener( new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {
                                                        Intent intent = new Intent(MainActivity.this, LiveStation.class);
                                                        startActivity(intent);
                                                    }
                                                });
                                            }

                                        } else {
                                            Log.w(TAG, "Station not found");
                                        }
                                    } else {
                                        Log.w(TAG, "Unable to get station");
                                    }
                                }
                            });
                        }
                    }
                }

                Log.d( TAG, "Document Snapshot: " + document.getData() );

            } else {
                Log.w(TAG, "No document found");
            }
        } else {
            Log.w(TAG, "Get user stations failed: " + task.getException() );
        }
    }
});

我对Android中的异步调用不是很熟悉。通常我创建一个与数据库对话的模型,它可以从应用程序结构中的任何地方调用,但使用Firebase似乎我不能这样做。似乎每个视图都需要自己对数据库的唯一调用。或许我把整个想法弄错了。

0 个答案:

没有答案