How to combine Android Firebase Database, LiveData and ViewModel

In this android programming source code example, we are going to combine Android Firebase Database, LiveData and ViewModel.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to combine Android Firebase Database, LiveData and ViewModel.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15dp"
    android:background="#CACACA">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="title"
        android:textSize="20sp"
        android:layout_marginTop="90dp"/>

    <View
        android:id="@+id/view1"
        android:layout_width="match_parent"
        android:layout_height="2sp"
        android:layout_below="@id/title"
        android:background="@color/colorAccent"/>

    <TextView
        android:id="@+id/body"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="body"
        android:textSize="30sp"
        android:layout_below="@id/view1"/>

</RelativeLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.widget.TextView;

import com.google.firebase.database.DataSnapshot;

public class FirebaseActivity7 extends AppCompatActivity {
    private TextView title;
    private TextView body;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firebase7);
        title = (TextView)findViewById(R.id.title);
        body = (TextView)findViewById(R.id.body);
        ViewModel7 viewModel7 = ViewModelProviders.of(this).get(ViewModel7.class);
        LiveData<DataSnapshot>liveData = viewModel7.getdataSnapshotLiveData();
        liveData.observe(this, new Observer<DataSnapshot>() {
            @Override
            public void onChanged(DataSnapshot dataSnapshot) {
                if(dataSnapshot != null){
                    for(DataSnapshot readData: dataSnapshot.getChildren()){
                        Data data = readData.getValue(Data.class);
                         title.setText(data.getTitle());
                         body.setText(data.getContent());
                    }
                }
            }
        });
    }
}

ViewModel7.java

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class ViewModel7 extends ViewModel {
    private static final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("AndroidView");
    private final FirebaseQueryLiveData liveData = new FirebaseQueryLiveData(mDatabase);

    @NonNull
    public LiveData<DataSnapshot> getdataSnapshotLiveData(){
        return liveData;
    }

}

FirebaseQueryLiveData.java

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

public class FirebaseQueryLiveData extends LiveData<DataSnapshot> {
    private static final String Log_tag = "FirebaseQueryLiveData";
    private final Query query;
    private final MyValueEventListner listner = new MyValueEventListner();

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

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

    private class MyValueEventListner implements ValueEventListener{

        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            setValue(dataSnapshot);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.d(Log_tag, "Can't listened to query "+query, databaseError.toException());
        }
    }
}

Data.java

public class Data {
    public String title, content;

    public Data(){

    }

    public Data(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public String getTitle() {
        return title;
    }

    public String getContent() {
        return content;
    }

}

 

app/build.gradle

implementation 'androidx.lifecycle:lifecycle-viewmodel:2.0.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.google.firebase:firebase-database:17.0.0'

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment