简体   繁体   English

如何在 Android 中使用 LiveData 和 ViewModel 不断更新 Firebase 实时数据库的查询

[英]How to constantly update query for Firebase Realtime Database with LiveData and ViewModel in Android

I use Firebase Realtime Database and LiveData with ViewModel in Android and I would like to constantly update the query.我在 Android 中使用 Firebase 实时数据库和 LiveData 和 ViewModel,我想不断更新查询。

Here is the ViewModel class:这是 ViewModel 类:

public class ViewModel_MainActivity extends ViewModel {


    /*
    LiveData with Database query for the Firebase node "Ratings"
    */

    private static long currentTimeMillisRating = System.currentTimeMillis();
    private static double pastMinuteForDisplayingRatings = 1;
    private static long pastTimeMillisRatings = System.currentTimeMillis() - (long) (pastMinuteForDisplayingRatings * 60 * 60 * 1000);


    private static final Query QUERY_RATINGS =
            FirebaseDatabase.getInstance(DB_SQLite_Firebase_Entries.FIREBASE_URL).getReference().child(DB_SQLite_Firebase_Entries.FIREBASE_NODE_RATINGS).orderByChild(DB_SQLite_Firebase_Entries.FIREBASE_RATINGDATEINMILLISECONDS).endAt(pastTimeMillisRatings);


    private final LiveData_FirebaseRating liveData_firebaseRating = new LiveData_FirebaseRating(QUERY_RATINGS);

    @NonNull
    public LiveData_FirebaseRating getDataSnapshotLiveData_FirebaseRating() {
        Log.e("LogTag_ViMo", "pastTimeMillisRatings: " + pastTimeMillisRatings);
        return liveData_firebaseRating;
    }


}

Here is the LiveData class:这是 LiveData 类:

public class LiveData_FirebaseRating extends LiveData<DataSnapshot> {
    private static final String LOG_TAG = "LiveData_FirebaseRating";

    private Query query;
    private final LiveData_FirebaseRating.MyValueEventListener listener = new LiveData_FirebaseRating.MyValueEventListener();

    DataSnapshot currentDataSnapShotFromFirebase;

    public LiveData_FirebaseRating(Query query) {
        this.query = query;
    }

    public LiveData_FirebaseRating(DatabaseReference ref) {
        this.query = ref;
    }

    public void changeQuery(Query newQuery) {
        this.query = newQuery;
    }

    public DataSnapshot getCurrentDataSnapShotFromFirebase() {
        return currentDataSnapShotFromFirebase;
    }

    public void setCurrentDataSnapShotFromFirebase(DataSnapshot currentDataSnapShotFromFirebase) {
        this.currentDataSnapShotFromFirebase = currentDataSnapShotFromFirebase;
    }

    @Override
    protected void onActive() {
        Log.d(LOG_TAG, "onActive");
        query.addValueEventListener(listener);
    }

    @Override
    protected void onInactive() {
        Log.d(LOG_TAG, "onInactive");
        query.removeEventListener(listener);
    }

    private class MyValueEventListener implements ValueEventListener {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {


            setValue(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e(LOG_TAG, "Can't listen to query " + query, databaseError.toException());
        }
    }
}

And here is the part of the main activity, where the live data and view model are created and observed:这是主要活动的一部分,其中创建和观察实时数据和视图模型:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
       
        /*
        Initiate View Model with LiveData for Firebase
         */



        rootRef_Firebase = FirebaseDatabase.getInstance(DB_SQLite_Firebase_Entries.FIREBASE_URL).getReference();
        viewModel = new ViewModelProvider(this).get(ViewModel_MainActivity.class);

        liveData_firebaseRating = viewModel.getDataSnapshotLiveData_FirebaseRating();
        liveData_firebaseRating.observe(this, new Observer<DataSnapshot>() {

            @Override
            public void onChanged(@Nullable DataSnapshot dataSnapshot) {
                liveData_firebaseRating.setCurrentDataSnapShotFromFirebase(dataSnapshot);
                if(liveData_firebaseRating.getCurrentDataSnapShotFromFirebase()!=null) {
                    //Do something with the dataSnapshot of the query
                }
            }// end onChange
        }); //end observe



    }

So my problem lies in the non-updating of the QUERY_RATINGS in the class ViewModel_MainActivity .所以我的问题在于ViewModel_MainActivity类中的QUERY_RATINGS没有更新。 What I want is to return all the nodes from the FIREBASE_NODE_RATINGS whose at attribute FIREBASE_RATINGDATEINMILLISECONDS is older than 1 Minute (meaning that the entry was created at least 1 Minute before the current time slot).我想要的是从FIREBASE_NODE_RATINGS返回所有节点,其 at 属性FIREBASE_RATINGDATEINMILLISECONDS早于 1 分钟(这意味着该条目是在当前时隙之前至少 1 分钟创建的)。 How can I do that such that I always get these nodes?我怎样才能做到这一点,以便我总是得到这些节点?

Firebase Query objects are immutable, and their parameters are fixed values. Firebase Query对象是不可变的,它们的参数是固定值。 So there is no way to update the existing query, nor is there a "one minute ago" value that automatically updates.所以没有办法更新现有的查询,也没有自动更新的“一分钟前”值。

The options I can quickly think off:我能很快想到的选项:

  • Create a new query frequently to capture the new full range of relevant nodes.频繁创建新查询以捕获新的全范围相关节点。
  • Create a new query frequently to capture only the new nodes (by combining startAt and endAt ) and merge them with the results you already have.经常创建一个新查询以仅捕获新节点(通过组合startAtendAt )并将它们与您已有的结果合并。
  • Remove the condition from the query, and perform the filtering in your application code.从查询中删除条件,并在您的应用程序代码中执行过滤。

Based on what I know, I'd probably start with the third option as it seems the simplest.根据我所知道的,我可能会从第三种选择开始,因为它似乎是最简单的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM