首页 > 解决方案 > Android:如何使用 Firebase 正确获取数据?

问题描述

我正在使用 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 似乎我无法做到这一点。似乎每个视图都需要对数据库进行独特的调用。或者,也许我的整个想法都错了。

标签: androidfirebaseasynchronousgoogle-cloud-firestore

解决方案


推荐阅读