使用Firebase的Android架构组件专门为Firestore

时间:2018-04-12 14:11:37

标签: android firebase firebase-realtime-database google-cloud-firestore

blog Doug Stevenson(Firebase开发者倡导者)正在审核此{{3}} 该博客讨论了如何将 firebase实时数据库与android体系结构组件一起使用。

有一个类FirebaseQueryLiveData,它构成了一个可重用的类来管理所有Firebase查询以及实现LiveData。这虽然完全适用于Firebase RealTime数据库,我似乎无法更改或更改它以支持云端防火墙数据库。

这是代码

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

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

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

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

    @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());
        }
    }
}

4 个答案:

答案 0 :(得分:7)

这是@JobM帖子的查询版本。谢谢@JobM!为清楚起见,我建议将@ JobM的版本重命名为FirebaseDocumentLiveData。

import android.arch.lifecycle.LiveData;
import android.os.Handler;
import android.util.Log;

import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.ListenerRegistration;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;

import javax.annotation.Nullable;

public class FirebaseQueryLiveData extends LiveData<QuerySnapshot> {
    public static final String TAG = "FbaseQueryLiveData";

    private Query query;
    private final MyValueEventListener listener = new MyValueEventListener();
    private ListenerRegistration listenerRegistration;

    private boolean listenerRemovePending = false;
    private final Handler handler = new Handler();

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

    private final Runnable removeListener = new Runnable() {
        @Override
        public void run() {
            listenerRegistration.remove();
            listenerRemovePending = false;
        }
    };

    @Override
    protected void onActive() {
        super.onActive();

        Log.d(TAG, "onActive");
        if (listenerRemovePending) {
            handler.removeCallbacks(removeListener);
        }
        else {
            listenerRegistration = query.addSnapshotListener(listener);
        }
        listenerRemovePending = false;
    }

    @Override
    protected void onInactive() {
        super.onInactive();

        Log.d(TAG, "onInactive: ");
        // Listener removal is schedule on a two second delay
        handler.postDelayed(removeListener, 2000);
        listenerRemovePending = true;
    }

    private class MyValueEventListener implements EventListener<QuerySnapshot> {
        @Override
        public void onEvent(@Nullable QuerySnapshot querySnapshot, @Nullable FirebaseFirestoreException e) {
            if (e != null){
                Log.e(TAG, "Can't listen to query snapshots: " + querySnapshot + ":::" + e.getMessage());
                return;
            }
            setValue(querySnapshot);
        }
    }
}

答案 1 :(得分:3)

对于Kotlin的恋人:)

import android.os.Handler
import androidx.annotation.Nullable
import androidx.lifecycle.LiveData
import com.google.firebase.firestore.*
import timber.log.Timber

class FirebaseQueryLiveData(private val query: Query) : LiveData<QuerySnapshot>() {
private val listener = MyValueEventListener()
private var listenerRegistration: ListenerRegistration? = null

private var listenerRemovePending = false
private val handler = Handler()

private val removeListener = Runnable {
    listenerRegistration!!.remove()
    listenerRemovePending = false
}

override fun onActive() {
    super.onActive()

    Timber.d( "onActive")
    if (listenerRemovePending) {
        handler.removeCallbacks(removeListener)
    } else {
        listenerRegistration = query.addSnapshotListener(listener)
    }
    listenerRemovePending = false
}

override fun onInactive() {
    super.onInactive()

    Timber.d("onInactive: ")
    // Listener removal is schedule on a two second delay
    handler.postDelayed(removeListener, 2000)
    listenerRemovePending = true
}

private inner class MyValueEventListener : EventListener<QuerySnapshot> {
    override fun onEvent(@Nullable querySnapshot: QuerySnapshot?, @Nullable e: FirebaseFirestoreException?) {
        if (e != null) {
            Timber.e(e, "Can't listen to query snapshots: %s", querySnapshot)
            return
        }
        value = querySnapshot
    }
}

}

答案 2 :(得分:2)

import android.arch.lifecycle.LiveData;
import android.support.annotation.Nullable;
import android.util.Log;

import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.ListenerRegistration;

/**
 * Created by Job on Thursday : 4/12/2018.
 */
public class FirebaseQueryLiveData extends LiveData<DocumentSnapshot> {

    public static final String TAG = "FirebaseQueryLiveData";
    private DocumentReference documentReference;
    private final MyValueEventListener listener = new MyValueEventListener();
    private ListenerRegistration listenerRegistration;

    public FirebaseQueryLiveData(DocumentReference documentReference) {
        this.documentReference = documentReference;
    }

    @Override
    protected void onActive() {
        super.onActive();

        Log.d(TAG, "onActive");
        if (listenerRegistration == null )
        listenerRegistration = documentReference.addSnapshotListener(listener);
    }

    @Override
    protected void onInactive() {
        super.onInactive();

        Log.d(TAG, "onInactive: ");
        if (listenerRegistration != null)
        listenerRegistration.remove();
    }

    private class MyValueEventListener implements EventListener<DocumentSnapshot> {
        @Override
        public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
            if (e != null){
                Log.e(TAG, "Can't listen to doc snapshots: " + documentSnapshot + ":::" + e.getMessage());
                return;
            }
            setValue(documentSnapshot);
        }
    }
}

此类仅显示如何检索文档。这也是查询。

答案 3 :(得分:1)

@Andre Silveira 您想要的是FirebaseQueryLiveData的此类

import android.arch.lifecycle.LiveData;
import android.os.Handler;
import android.util.Log;

import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.ListenerRegistration;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;

/**
 * Created by Job on Thursday : 5/31/2018.
 */
public class FirebaseQueryLiveData  extends LiveData<QuerySnapshot> {


    public static final String TAG = "FireDocLiveData";
    private Query query;
    private final FirebaseQueryLiveData.MyValueEventListener listener = new FirebaseQueryLiveData.MyValueEventListener();
    private ListenerRegistration listenerRegistration;

    private boolean listenerRemovePending = false;
    private final Handler handler = new Handler();


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


    private final Runnable removeListener = new Runnable() {
        @Override
        public void run() {

            Log.d(TAG, "onInactive: removeListener");
            if (listenerRegistration != null) {
                listenerRegistration.remove();
            }
            listenerRemovePending = false;
        }
    };


    @Override
    protected void onActive() {
        super.onActive();

        Log.d(TAG, "onActive");

        if (listenerRemovePending){

            handler.removeCallbacks(removeListener);

        }else {
            if (listenerRegistration == null) {
                listenerRegistration = query.addSnapshotListener(listener);
            }
        }

        listenerRemovePending = false;
    }

    @Override
    protected void onInactive() {
        super.onInactive();

        Log.d(TAG, "onInactive: onInactive()");


        // Listener removal is schedule on a two second delay
        // This is to save on counts against the quota or the bill of Firebase :)
        handler.postDelayed(removeListener, 2000);
        listenerRemovePending = true;

    }

    private class MyValueEventListener implements EventListener<QuerySnapshot> {
        @Override
        public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
            if (e != null){
                Log.e(TAG, "Can't listen to doc snapshots: " + queryDocumentSnapshots + ":::" + e.getMessage());
                return;
            }
            setValue(queryDocumentSnapshots);
        }
    }
}