Firebase Cloud Firestore Database Example in Android Android by Rajesh Kumar Sahanee - March 15, 2020April 14, 20200 Post Views: 4,483 Hello Friends, today we are going to see Firebase Cloud Firestore database example in Android. Cloud Firestore is a NoSQL flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform. To use cloud firestore in our android project we first need to setup project and app on firebase console and download configuration file. Here I’ll not explain how to setup project, app and download configuration file as it is better explained on official website. We’ll see only coding and adding dependency part here and to setup project, app and downloading configuration file below link will help us. https://firebase.google.com/docs/android/setup#console So, here is the code build.gradle (Project Level) build.gradle // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.6.1' classpath 'com.google.gms:google-services:4.3.3'//added // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } 123456789101112131415161718192021222324252627282930 // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.6.1' classpath 'com.google.gms:google-services:4.3.3'//added // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }} allprojects { repositories { google() jcenter() }} task clean(type: Delete) { delete rootProject.buildDir} build.gradle (Module Level) build.gradle apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services'//added android { compileSdkVersion 28 defaultConfig { applicationId "com.zatackcoder.firebasedatabaseexample" minSdkVersion 16 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" //to fix Cannot fit requested classes in a single dex file error multiDexEnabled true //added } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' implementation 'com.google.firebase:firebase-auth:19.2.0' //added implementation 'com.google.firebase:firebase-firestore:21.4.1' //added implementation 'com.firebaseui:firebase-ui-firestore:4.1.0' //added implementation 'androidx.recyclerview:recyclerview:1.1.0' //added //Cannot fit requested classes in a single dex file implementation 'com.android.support:multidex:1.0.3' //added } 1234567891011121314151617181920212223242526272829303132333435363738394041424344 apply plugin: 'com.android.application'apply plugin: 'com.google.gms.google-services'//added android { compileSdkVersion 28 defaultConfig { applicationId "com.zatackcoder.firebasedatabaseexample" minSdkVersion 16 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" //to fix Cannot fit requested classes in a single dex file error multiDexEnabled true //added } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' implementation 'com.google.firebase:firebase-auth:19.2.0' //added implementation 'com.google.firebase:firebase-firestore:21.4.1' //added implementation 'com.firebaseui:firebase-ui-firestore:4.1.0' //added implementation 'androidx.recyclerview:recyclerview:1.1.0' //added //Cannot fit requested classes in a single dex file implementation 'com.android.support:multidex:1.0.3' //added} MainActivity.java MainActivity.java Java package com.zatackcoder.firebasedatabaseexample; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initControls(); } private void initControls() { Button addItemB = findViewById(R.id.addItemB); Button viewItemsB = findViewById(R.id.viewItemsB); addItemB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, AddItemActivity.class)); } }); viewItemsB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, ViewItemsActivity.class)); } }); } } 1234567891011121314151617181920212223242526272829303132333435363738 package com.zatackcoder.firebasedatabaseexample; import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initControls(); } private void initControls() { Button addItemB = findViewById(R.id.addItemB); Button viewItemsB = findViewById(R.id.viewItemsB); addItemB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, AddItemActivity.class)); } }); viewItemsB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, ViewItemsActivity.class)); } }); }} activity_main.xml activity_main.xml XHTML <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <Button android:id="@+id/addItemB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add Item" /> <Button android:id="@+id/viewItemsB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="View Items" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> 1234567891011121314151617181920212223242526272829 <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <Button android:id="@+id/addItemB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add Item" /> <Button android:id="@+id/viewItemsB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="View Items" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> Item.java Item.java Java package com.zatackcoder.firebasedatabaseexample; public class Item { private String name; private String color; private Integer size; private Double price; public Item() { } public Item(String name, String color, Integer size, Double price) { this.name = name; this.color = color; this.size = size; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public Integer getSize() { return size; } //customised setter to overcome deserialize object error //java.lang.RuntimeException: Could not deserialize object. Failed to convert a value of type java.lang.String to int public void setSize(Object size) { try { this.size = Integer.parseInt(size.toString()); } catch (Exception e) { this.size = 0; } } public Double getPrice() { return price; } //customised setter to overcome deserialize object error //java.lang.RuntimeException: Could not deserialize object. Failed to convert a value of type java.lang.String to double public void setPrice(Object price) { try { this.price = Double.parseDouble(price.toString()); } catch (Exception e) { this.price = 0.00; } } } 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 package com.zatackcoder.firebasedatabaseexample; public class Item { private String name; private String color; private Integer size; private Double price; public Item() { } public Item(String name, String color, Integer size, Double price) { this.name = name; this.color = color; this.size = size; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public Integer getSize() { return size; } //customised setter to overcome deserialize object error //java.lang.RuntimeException: Could not deserialize object. Failed to convert a value of type java.lang.String to int public void setSize(Object size) { try { this.size = Integer.parseInt(size.toString()); } catch (Exception e) { this.size = 0; } } public Double getPrice() { return price; } //customised setter to overcome deserialize object error //java.lang.RuntimeException: Could not deserialize object. Failed to convert a value of type java.lang.String to double public void setPrice(Object price) { try { this.price = Double.parseDouble(price.toString()); } catch (Exception e) { this.price = 0.00; } }} AddItemActivity.java AddItemActivity.java Java package com.zatackcoder.firebasedatabaseexample; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; public class AddItemActivity extends AppCompatActivity { FirebaseFirestore db; EditText nameET; EditText colorET; EditText sizeET; EditText priceET; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_item); // Access a Cloud Firestore instance from your Activity db = FirebaseFirestore.getInstance(); initControls(); } private void initControls() { nameET = findViewById(R.id.nameET); colorET = findViewById(R.id.colorET); sizeET = findViewById(R.id.sizeET); priceET = findViewById(R.id.priceET); Button saveB = findViewById(R.id.saveB); saveB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Item item = new Item(nameET.getText().toString(), colorET.getText().toString(), Integer.parseInt(sizeET.getText().toString()), Double.parseDouble(priceET.getText().toString())); // Add a new document with a generated ID db.collection("items") .add(item) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { nameET.setText(""); colorET.setText(""); sizeET.setText(""); priceET.setText(""); Toast.makeText(getApplicationContext(), "Item Added with ID: " + documentReference.getId(), Toast.LENGTH_LONG).show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getApplicationContext(), "Error Adding Item! - " + e, Toast.LENGTH_LONG).show(); } }); } }); } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 package com.zatackcoder.firebasedatabaseexample; import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.FirebaseFirestore; public class AddItemActivity extends AppCompatActivity { FirebaseFirestore db; EditText nameET; EditText colorET; EditText sizeET; EditText priceET; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_item); // Access a Cloud Firestore instance from your Activity db = FirebaseFirestore.getInstance(); initControls(); } private void initControls() { nameET = findViewById(R.id.nameET); colorET = findViewById(R.id.colorET); sizeET = findViewById(R.id.sizeET); priceET = findViewById(R.id.priceET); Button saveB = findViewById(R.id.saveB); saveB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Item item = new Item(nameET.getText().toString(), colorET.getText().toString(), Integer.parseInt(sizeET.getText().toString()), Double.parseDouble(priceET.getText().toString())); // Add a new document with a generated ID db.collection("items") .add(item) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { nameET.setText(""); colorET.setText(""); sizeET.setText(""); priceET.setText(""); Toast.makeText(getApplicationContext(), "Item Added with ID: " + documentReference.getId(), Toast.LENGTH_LONG).show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getApplicationContext(), "Error Adding Item! - " + e, Toast.LENGTH_LONG).show(); } }); } }); }} activity_add_item.xml activity_add_item.xml XHTML <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.zatackcoder.firebasedatabaseexample.AddItemActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add Item" android:textSize="18sp" android:textStyle="bold" /> <EditText android:id="@+id/nameET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:ems="10" android:hint="Name" /> <EditText android:id="@+id/colorET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Color" /> <EditText android:id="@+id/sizeET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Size" /> <EditText android:id="@+id/priceET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Price" /> <Button android:id="@+id/saveB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="Save" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.zatackcoder.firebasedatabaseexample.AddItemActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add Item" android:textSize="18sp" android:textStyle="bold" /> <EditText android:id="@+id/nameET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:ems="10" android:hint="Name" /> <EditText android:id="@+id/colorET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Color" /> <EditText android:id="@+id/sizeET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Size" /> <EditText android:id="@+id/priceET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Price" /> <Button android:id="@+id/saveB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="Save" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> ItemAdapter.java ItemAdapter.java Java package com.zatackcoder.firebasedatabaseexample; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.firebase.ui.firestore.FirestoreRecyclerAdapter; import com.firebase.ui.firestore.FirestoreRecyclerOptions; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; public class ItemAdapter extends FirestoreRecyclerAdapter<Item, ItemAdapter.ItemViewHolder> { Context context; /** * Create a new RecyclerView adapter that listens to a Firestore Query. See {@link * FirestoreRecyclerOptions} for configuration options. * * @param options */ public ItemAdapter(Context context, @NonNull FirestoreRecyclerOptions<Item> options) { super(options); this.context = context; } @NonNull @Override public ItemAdapter.ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); return new ItemAdapter.ItemViewHolder(view); } @Override protected void onBindViewHolder(@NonNull final ItemAdapter.ItemViewHolder itemViewHolder, int i, @NonNull Item item) { itemViewHolder.name.setText(item.getName()); itemViewHolder.color.setText("Color: " + item.getColor()); itemViewHolder.size.setText("Size: " + item.getSize().toString()); itemViewHolder.price.setText("Price: " + item.getPrice().toString()); final String documentId = getSnapshots().getSnapshot(i).getId(); itemViewHolder.edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(context, EditItemActivity.class); i.putExtra("documentId", documentId); context.startActivity(i); } }); itemViewHolder.delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FirebaseFirestore db = FirebaseFirestore.getInstance(); db.collection("items").document(documentId) .delete() .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(context, "Item deleted successfully!", Toast.LENGTH_LONG).show(); } }); } }); } @Override public void onError(@NonNull FirebaseFirestoreException e) { //super.onError(e); } public static class ItemViewHolder extends RecyclerView.ViewHolder { View container; TextView name; TextView color; TextView size; TextView price; Button edit; Button delete; public ItemViewHolder(View view) { super(view); container = view; name = view.findViewById(R.id.name); color = view.findViewById(R.id.color); size = view.findViewById(R.id.size); price = view.findViewById(R.id.price); edit = view.findViewById(R.id.edit); delete = view.findViewById(R.id.delete); } } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 package com.zatackcoder.firebasedatabaseexample; import android.content.Context;import android.content.Intent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.firebase.ui.firestore.FirestoreRecyclerAdapter;import com.firebase.ui.firestore.FirestoreRecyclerOptions;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.firestore.FirebaseFirestore;import com.google.firebase.firestore.FirebaseFirestoreException; public class ItemAdapter extends FirestoreRecyclerAdapter<Item, ItemAdapter.ItemViewHolder> { Context context; /** * Create a new RecyclerView adapter that listens to a Firestore Query. See {@link * FirestoreRecyclerOptions} for configuration options. * * @param options */ public ItemAdapter(Context context, @NonNull FirestoreRecyclerOptions<Item> options) { super(options); this.context = context; } @NonNull @Override public ItemAdapter.ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); return new ItemAdapter.ItemViewHolder(view); } @Override protected void onBindViewHolder(@NonNull final ItemAdapter.ItemViewHolder itemViewHolder, int i, @NonNull Item item) { itemViewHolder.name.setText(item.getName()); itemViewHolder.color.setText("Color: " + item.getColor()); itemViewHolder.size.setText("Size: " + item.getSize().toString()); itemViewHolder.price.setText("Price: " + item.getPrice().toString()); final String documentId = getSnapshots().getSnapshot(i).getId(); itemViewHolder.edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(context, EditItemActivity.class); i.putExtra("documentId", documentId); context.startActivity(i); } }); itemViewHolder.delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FirebaseFirestore db = FirebaseFirestore.getInstance(); db.collection("items").document(documentId) .delete() .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(context, "Item deleted successfully!", Toast.LENGTH_LONG).show(); } }); } }); } @Override public void onError(@NonNull FirebaseFirestoreException e) { //super.onError(e); } public static class ItemViewHolder extends RecyclerView.ViewHolder { View container; TextView name; TextView color; TextView size; TextView price; Button edit; Button delete; public ItemViewHolder(View view) { super(view); container = view; name = view.findViewById(R.id.name); color = view.findViewById(R.id.color); size = view.findViewById(R.id.size); price = view.findViewById(R.id.price); edit = view.findViewById(R.id.edit); delete = view.findViewById(R.id.delete); } }} list_item.xml list_item.xml XHTML <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:background="#ffffff" android:clickable="true" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?android:attr/selectableItemBackground" android:orientation="vertical" android:padding="5dp"> <TextView android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Name" android:textFontWeight="bold" android:textSize="15dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/color" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Color: Red" android:textSize="12dp" /> <View android:layout_width="1dp" android:layout_height="match_parent" android:layout_margin="5dp" android:background="#ADABAB" /> <TextView android:id="@+id/size" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Size: 10" android:textSize="12dp" /> <View android:layout_width="1dp" android:layout_height="match_parent" android:layout_margin="5dp" android:background="#ADABAB" /> <TextView android:id="@+id/price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Price: 100" android:textSize="12dp" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/edit" android:layout_width="wrap_content" android:layout_height="35dp" android:textSize="10dp" android:text="Edit" /> <Button android:id="@+id/delete" android:layout_width="wrap_content" android:layout_height="35dp" android:textSize="10dp" android:textColor="#F00" android:text="Delete"/> </LinearLayout> </LinearLayout> </LinearLayout> 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:background="#ffffff" android:clickable="true" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?android:attr/selectableItemBackground" android:orientation="vertical" android:padding="5dp"> <TextView android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Name" android:textFontWeight="bold" android:textSize="15dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/color" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Color: Red" android:textSize="12dp" /> <View android:layout_width="1dp" android:layout_height="match_parent" android:layout_margin="5dp" android:background="#ADABAB" /> <TextView android:id="@+id/size" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Size: 10" android:textSize="12dp" /> <View android:layout_width="1dp" android:layout_height="match_parent" android:layout_margin="5dp" android:background="#ADABAB" /> <TextView android:id="@+id/price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Price: 100" android:textSize="12dp" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/edit" android:layout_width="wrap_content" android:layout_height="35dp" android:textSize="10dp" android:text="Edit" /> <Button android:id="@+id/delete" android:layout_width="wrap_content" android:layout_height="35dp" android:textSize="10dp" android:textColor="#F00" android:text="Delete"/> </LinearLayout> </LinearLayout> </LinearLayout> ViewItemsActivity.java ViewItemsActivity.java Java package com.zatackcoder.firebasedatabaseexample; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.firebase.ui.firestore.FirestoreRecyclerOptions; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Query; public class ViewItemsActivity extends AppCompatActivity { FirebaseFirestore db; private RecyclerView mRecyclerView; private RecyclerView.LayoutManager mLayoutManager; private ItemAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_items); setTitle("Items"); mRecyclerView = findViewById(R.id.recycler_view); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); db = FirebaseFirestore.getInstance(); Query query = db.collection("items").orderBy("name", Query.Direction.ASCENDING); FirestoreRecyclerOptions<Item> options = new FirestoreRecyclerOptions.Builder<Item>() .setQuery(query, Item.class) .build(); adapter = new ItemAdapter(this, options); mRecyclerView.setAdapter(adapter); } @Override protected void onStart() { super.onStart(); adapter.startListening(); } @Override protected void onStop() { super.onStop(); if (adapter != null) { adapter.stopListening(); } } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 package com.zatackcoder.firebasedatabaseexample; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.firebase.ui.firestore.FirestoreRecyclerOptions;import com.google.firebase.firestore.FirebaseFirestore;import com.google.firebase.firestore.Query; public class ViewItemsActivity extends AppCompatActivity { FirebaseFirestore db; private RecyclerView mRecyclerView; private RecyclerView.LayoutManager mLayoutManager; private ItemAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_items); setTitle("Items"); mRecyclerView = findViewById(R.id.recycler_view); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); db = FirebaseFirestore.getInstance(); Query query = db.collection("items").orderBy("name", Query.Direction.ASCENDING); FirestoreRecyclerOptions<Item> options = new FirestoreRecyclerOptions.Builder<Item>() .setQuery(query, Item.class) .build(); adapter = new ItemAdapter(this, options); mRecyclerView.setAdapter(adapter); } @Override protected void onStart() { super.onStart(); adapter.startListening(); } @Override protected void onStop() { super.onStop(); if (adapter != null) { adapter.stopListening(); } }} activity_view_items.xml activity_view_items.xml XHTML <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="5dp" tools:context=".ViewItemsActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" tools:layout_editor_absoluteX="1dp" tools:layout_editor_absoluteY="1dp" /> </androidx.constraintlayout.widget.ConstraintLayout> 123456789101112131415161718 <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="5dp" tools:context=".ViewItemsActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" tools:layout_editor_absoluteX="1dp" tools:layout_editor_absoluteY="1dp" /> </androidx.constraintlayout.widget.ConstraintLayout> EditItemActivity.java EditItemActivity.java Java package com.zatackcoder.firebasedatabaseexample; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import java.util.HashMap; import java.util.Map; public class EditItemActivity extends AppCompatActivity { FirebaseFirestore db; EditText nameET; EditText colorET; EditText sizeET; EditText priceET; String documentId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_item); db = FirebaseFirestore.getInstance(); Intent i = getIntent(); documentId = i.getStringExtra("documentId"); if(documentId == null || documentId.isEmpty()) { startActivity(new Intent(this, ViewItemsActivity.class)); finish(); } initControls(); } private void initControls() { nameET = findViewById(R.id.nameET); colorET = findViewById(R.id.colorET); sizeET = findViewById(R.id.sizeET); priceET = findViewById(R.id.priceET); Button saveB = findViewById(R.id.saveB); saveB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Item item = new Item(nameET.getText().toString(), colorET.getText().toString(), Integer.parseInt(sizeET.getText().toString()), Double.parseDouble(priceET.getText().toString())); // Update a existing document with a document ID db.collection("items").document(documentId) .set(item) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(getApplicationContext(), "Item Updated with ID: " + documentId, Toast.LENGTH_LONG).show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getApplicationContext(), "Error Updating Item! - " + e, Toast.LENGTH_LONG).show(); } }); } }); DocumentReference docRef = db.collection("items").document(documentId); docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { Item item = documentSnapshot.toObject(Item.class); nameET.setText(item.getName()); colorET.setText(item.getColor()); sizeET.setText(item.getSize().toString()); priceET.setText(item.getPrice().toString()); } }); } } 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 package com.zatackcoder.firebasedatabaseexample; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.DocumentSnapshot;import com.google.firebase.firestore.FirebaseFirestore; import java.util.HashMap;import java.util.Map; public class EditItemActivity extends AppCompatActivity { FirebaseFirestore db; EditText nameET; EditText colorET; EditText sizeET; EditText priceET; String documentId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_item); db = FirebaseFirestore.getInstance(); Intent i = getIntent(); documentId = i.getStringExtra("documentId"); if(documentId == null || documentId.isEmpty()) { startActivity(new Intent(this, ViewItemsActivity.class)); finish(); } initControls(); } private void initControls() { nameET = findViewById(R.id.nameET); colorET = findViewById(R.id.colorET); sizeET = findViewById(R.id.sizeET); priceET = findViewById(R.id.priceET); Button saveB = findViewById(R.id.saveB); saveB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Item item = new Item(nameET.getText().toString(), colorET.getText().toString(), Integer.parseInt(sizeET.getText().toString()), Double.parseDouble(priceET.getText().toString())); // Update a existing document with a document ID db.collection("items").document(documentId) .set(item) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(getApplicationContext(), "Item Updated with ID: " + documentId, Toast.LENGTH_LONG).show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getApplicationContext(), "Error Updating Item! - " + e, Toast.LENGTH_LONG).show(); } }); } }); DocumentReference docRef = db.collection("items").document(documentId); docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { Item item = documentSnapshot.toObject(Item.class); nameET.setText(item.getName()); colorET.setText(item.getColor()); sizeET.setText(item.getSize().toString()); priceET.setText(item.getPrice().toString()); } }); }} activity_edit_item.xml activity_edit_item.xml XHTML <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".EditItemActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Edit Item" android:textSize="18sp" android:textStyle="bold" /> <EditText android:id="@+id/nameET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:ems="10" android:hint="Name" /> <EditText android:id="@+id/colorET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Color" /> <EditText android:id="@+id/sizeET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Size" /> <EditText android:id="@+id/priceET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Price" /> <Button android:id="@+id/saveB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="Update" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".EditItemActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Edit Item" android:textSize="18sp" android:textStyle="bold" /> <EditText android:id="@+id/nameET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:ems="10" android:hint="Name" /> <EditText android:id="@+id/colorET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Color" /> <EditText android:id="@+id/sizeET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Size" /> <EditText android:id="@+id/priceET" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Price" /> <Button android:id="@+id/saveB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="Update" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> Screenshots AndroidStudio Project Download FirebaseDatabaseExample AndroidStudio Project 1 file(s) 32.72 MB Download Thanks for Stoping by If you find this helpful then please do share