Hey guys, here is the complete Firebase Realtime Database Android with Java guide. Firebase realtime database is NoSQL database which means we don’t have the traditional columns and rows.
In firebase realtime database we can store data in the form of JSON tree structure like below.
In this post we will create an app in which we will perform the CRUD operation of firebase realtime database (Create, Read, Update and Delete).
Firebase Realtime Database Video Tutorial
If you are more comfortable in learning with video tutorials, then here is the tutorial playlist of Firebase Realtime Database Android Java.
Firebase Realtime Database CRUD Operations
First of all create a new android project and then you will need to connect your android with firebase to use firebase realtime database in your android project.
Below is the detailed video tutorial of How to create new Firebase project and how to connect that project with your android project.
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public class MainActivity extends AppCompatActivity implements View.OnClickListener { Button btnInsertData; Button btnRetreiveData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnInsertData = findViewById(R.id.btnInsertData); btnRetreiveData = findViewById(R.id.btnRetreiveData); btnInsertData.setOnClickListener(this); btnRetreiveData.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btnInsertData: startActivity(new Intent(MainActivity.this,InsertingDataActivity.class)); break; case R.id.btnRetreiveData: startActivity(new Intent(MainActivity.this,RetreiveDataActivity.class)); break; } } } |
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="12dp" android:background="#059BE5" tools:context=".MainActivity"> <ImageView android:layout_width="200dp" android:layout_height="200dp" android:src="@drawable/firebase_image" android:layout_gravity="center" android:textSize="45sp" android:gravity="center"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Firebase Realtime Database" android:fontFamily="sans-serif" android:textColor="#000000" android:textSize="45sp" android:gravity="center"/> <Button android:id="@+id/btnInsertData" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Insert Data" android:textAllCaps="false"/> <Button android:id="@+id/btnRetreiveData" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Retreive Data" android:textAllCaps="false"/> </LinearLayout> |
InsertingDataActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
public class InsertingDataActivity extends AppCompatActivity { EditText etName; EditText etRollno; Spinner spinnerCourses; Button btnInsertData; DatabaseReference studentDbRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inserting_data); etName = findViewById(R.id.etName); etRollno = findViewById(R.id.etRollno); spinnerCourses = findViewById(R.id.spinnerCourse); btnInsertData = findViewById(R.id.btnInsertData); studentDbRef = FirebaseDatabase.getInstance().getReference("Students"); btnInsertData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { insertStudentData(); } }); } private void insertStudentData(){ String name = etName.getText().toString(); String rollno = etRollno.getText().toString(); String course = spinnerCourses.getSelectedItem().toString(); String id = studentDbRef.push().getKey(); Students students = new Students(id,name,rollno,course); assert id != null; studentDbRef.child(id).setValue(students); Toast.makeText(InsertingDataActivity.this,"Data inserted!",Toast.LENGTH_SHORT).show(); } } |
activity_inserting_data.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="12dp" android:background="#059BE5" tools:context=".MainActivity"> <ImageView android:layout_width="200dp" android:layout_height="200dp" android:src="@drawable/firebase_image" android:layout_gravity="center" android:textSize="45sp" android:gravity="center"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Inserting data" android:fontFamily="sans-serif" android:textColor="#000000" android:textSize="45sp" android:gravity="center"/> <EditText android:id="@+id/etName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter name" android:layout_marginTop="20dp"/> <EditText android:id="@+id/etRollno" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter rollno" android:layout_marginTop="20dp"/> <Spinner android:id="@+id/spinnerCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:entries="@array/courses"/> <Button android:id="@+id/btnInsertData" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Insert Data" android:textAllCaps="false"/> </LinearLayout> |
RetrieveDataActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
public class RetreiveDataActivity extends AppCompatActivity { ListView myListview; List<Students> studentsList; DatabaseReference studentDbRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_retreive_data); myListview = findViewById(R.id.myListView); studentsList = new ArrayList<>(); studentDbRef = FirebaseDatabase.getInstance().getReference("Students"); studentDbRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { studentsList.clear(); for (DataSnapshot studentDatasnap : dataSnapshot.getChildren()){ Students students = studentDatasnap.getValue(Students.class); studentsList.add(students); } ListAdapter adapter = new ListAdapter(RetreiveDataActivity.this,studentsList); myListview.setAdapter(adapter); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); //set itemLong listener on listview item myListview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Students students = studentsList.get(position); showUpdateDialog(students.getId(), students.getName()); return false; } }); } private void showUpdateDialog(final String id, String name){ final AlertDialog.Builder mDialog = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); View mDialogView = inflater.inflate(R.layout.update_dialog, null); mDialog.setView(mDialogView); //create views refernces final EditText etUpdateName = mDialogView.findViewById(R.id.etUpdateName); final EditText etUpdateRollno = mDialogView.findViewById(R.id.etUpdateRollno); final Spinner mSpinner = mDialogView.findViewById(R.id.updateSpinner); Button btnUpdate = mDialogView.findViewById(R.id.btnUpdate); Button btnDelete = mDialogView.findViewById(R.id.btnDelete); mDialog.setTitle("Updating " + name +" record"); final AlertDialog alertDialog = mDialog.create(); alertDialog.show(); btnUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //here we will update data in database //now get values from view String newName = etUpdateName.getText().toString(); String newRollno = etUpdateRollno.getText().toString(); String newCourse = mSpinner.getSelectedItem().toString(); updateData(id,newName,newRollno,newCourse); Toast.makeText(RetreiveDataActivity.this, "Record Updated", Toast.LENGTH_SHORT).show(); alertDialog.dismiss(); } }); btnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deleteRecord(id); alertDialog.dismiss(); } }); } private void showToast(String message){ Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } private void deleteRecord(String id){ //create reference to database DatabaseReference DbRef = FirebaseDatabase.getInstance().getReference("Students").child(id); //we referencing child here because we will be delete one record not whole data data in database //we will use generic Task here so lets do it.. Task<Void> mTask = DbRef.removeValue(); mTask.addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { showToast("Deleted"); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { showToast("Error deleting record"); } }); } private void updateData(String id, String name, String rollno, String course){ //creating database reference DatabaseReference DbRef = FirebaseDatabase.getInstance().getReference("Students").child(id); Students students = new Students(id, name, rollno, course); DbRef.setValue(students); } } |
activity_retrieve_data.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" tools:context=".RetreiveDataActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Data Fetched From Firebase Database" android:textSize="30sp" android:gravity="center" android:textColor="#000000" android:layout_marginTop="10dp"/> <ListView android:id="@+id/myListView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="10dp" android:padding="5dp"/> </LinearLayout> |
ListAdapter.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public class ListAdapter extends ArrayAdapter { private Activity mContext; List<Students> studentsList; public ListAdapter(Activity mContext, List<Students> studentsList){ super(mContext,R.layout.list_item,studentsList); this.mContext = mContext; this.studentsList = studentsList; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater = mContext.getLayoutInflater(); View listItemView = inflater.inflate(R.layout.list_item,null,true); TextView tvName = listItemView.findViewById(R.id.tvName); TextView tvRollno = listItemView.findViewById(R.id.tvRollno); TextView tvCourse = listItemView.findViewById(R.id.tvCourse); Students students = studentsList.get(position); tvName.setText(students.getName()); tvRollno.setText(students.getRollno()); tvCourse.setText(students.getCourse()); return listItemView; } } |
Students.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public class Students { String id; String name; String rollno; String course; public Students() { } public Students(String id,String name, String rollno, String course) { this.id = id; this.name = name; this.rollno = rollno; this.course = course; } public String getId() { return id; } public String getName() { return name; } public String getRollno() { return rollno; } public String getCourse() { return course; } } |
list_item.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center_horizontal" android:padding="5dp"> <TextView android:id="@+id/tvName" android:layout_width="200dp" android:layout_height="wrap_content" android:text="name" android:gravity="center" android:textSize="24sp" android:textColor="#000000"/> <TextView android:id="@+id/tvRollno" android:layout_width="50dp" android:layout_height="wrap_content" android:text="roll no" android:textSize="24sp" android:layout_marginLeft="25dp" android:textColor="#000000"/> <TextView android:id="@+id/tvCourse" android:layout_width="100dp" android:layout_height="wrap_content" android:text="course" android:gravity="left" android:textSize="24sp" android:layout_marginLeft="25dp" android:textColor="#000000"/> </LinearLayout> |
update_dialog.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" android:padding="10dp"> <EditText android:id="@+id/etUpdateName" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName" android:hint="New name" /> <EditText android:id="@+id/etUpdateRollno" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:layout_marginTop="10dp" android:hint="New rollno" /> <Spinner android:id="@+id/updateSpinner" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/courses" android:layout_marginTop="10dp"/> <Button android:id="@+id/btnUpdate" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Update" /> <Button android:id="@+id/btnDelete" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Delete" /> </LinearLayout> |
So guys at this point our tutorial is completed and in the above steps we
performed the CRUD operations of Firebase Realtime Database with Java.
Happy Coding…