Hey guys here is the complete Firebase Realtime Database guide. Now days NoSQL databases are gaining popularity and Firebase Realtime Database is one of the NoSQL database.
In this tutorial we will learn modeling SQL tables to NoSQL Firebase Database. And then we will also learn the basic CRUD operation on the database (Create, Read, Update and Delete).
Table of Contents
- 1 Firebase Realtime Database Video Tutorial
- 2 Designing Database
- 3 Firebase Realtime Database Basics
- 4 Firebase Realtime Database Project
- 4.1 Creating Android Studio Project
- 4.2 Adding Firebase Database
- 4.3 Creating Activity Layouts
- 4.4 Defining Models
- 4.5 Saving an Artist
- 4.6 Retrieving Artists
- 4.7 Adding and Retrieving Tracks from Firebase Realtime Database
- 4.8 Updating Artist in Firebase Database
- 4.9 Deleting Artist from Firebase Realtime Database
Firebase Realtime Database Video Tutorial
- If you are more comfortable in learning with video tutorials, then here is the video tutorial series for Firebase Realtime Database.
Designing Database
- For this example I have following two tables.
- But firebase is not an SQL database and it does not stores data in tabular format. It uses JSON tree structure. So for firebase realtime database the structure for above database will be.
- I hope you got a clear understanding of the Firebase Realtime Database structure now. So lets jump into Android Studio.
Firebase Realtime Database Basics
- You have the database structure now you need to know the basic operations. So lets understand the steps of handling firebase database.
Getting Database Reference
- First we need to get the Firebase Database Reference. You can use DatabaseReference to get the reference.
1 2 3 4 |
private DatabaseReference mDatabase; mDatabase = FirebaseDatabase.getInstance().getReference("path"); //Dont pass any path if you want root of the tree |
- The data is stored in the JSON Tree form so you need to get the reference of an specified path. Like in the above database we can get all the Artists by passing “Artists”. If you want to access everything don’t pass anything and it will create a reference of the root of the tree.
Write Operation
- setValue() – This method will take a model java class object that will hold all the variables to be stored in the reference. The same method will be used to update the values at it overwrites the data of the specified reference. Â
- Suppose we have to store an Artist to our reference then we will create a model class as below.
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 |
@IgnoreExtraProperties public class Artist { private String artistId; private String artistName; private String artistGenre; public Artist(){ } public Artist(String artistId, String artistName, String artistGenre) { this.artistId = artistId; this.artistName = artistName; this.artistGenre = artistGenre; } public String getArtistId() { return artistId; } public String getArtistName() { return artistName; } public String getArtistGenre() { return artistGenre; } } |
- Now to save the artist we will use setValue() method.
1 2 3 4 |
Artist artist = new Artist(id, name, genre); databaseReference.child(id).setValue(artist); |
- The update operation will also be done in the same way.
Read Operation
- We will attache a ValueEventListener to the reference to read the data.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { } @Override public void onCancelled(DatabaseError databaseError) { } }); |
- Whenever you will change something in the Database the method onDataChange() will be executed. It contains all the data inside the specified path in the reference. We can use the DataSnapshot object to read all the data inside the reference. Â If some error occurres onCancelled() method will be called.
- onDataChange() method will also called once after the app launch and hence you can read the data at starting as well.
Delete Operation
- removeValue()Â can be used to delete the data.
- Now lets understand the operations in an Android Project.
Firebase Realtime Database Project
Creating Android Studio Project
- Open Android Studio and create a new project. In my case I have created FirebaseDatabaseExample.
- Now once your project is loaded completely, add Firebase Database in it.
Adding Firebase Database
- Go to tools -> Firebase, it will open an assistant. Now from the assistant go to Realtime Database.
- Connect to your Firebase Project and Setup the dependencies.
- Now you are ready to use Firebase Database in your project.
Creating Activity Layouts
- We need two activities. One is to add Artists and other one is to add Tracks to database. We will use MainActivity.java and activity_main.xml for Artists. But you need to create one more activity for Tracks. So I have created ArtistActivity and activity_artist.xml.Â
- Now first come inside activity_main.xml. Here we will create the following layout.
- As you can see the layout contains the following thing.
EditText: Here we will enter the name.
Spinner: Here we will give some genres so that we can select one of them.
Button: To save the new artist in Firebase.
ListView: To display all the saved artist from Firebase. - For creating this layout you can use the following xml code.
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 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="net.simplifiedcoding.firebasedatabaseexample.MainActivity"> <EditText android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter name" /> <Spinner android:id="@+id/spinnerGenres" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/editTextName" android:entries="@array/genres"></Spinner> <Button android:id="@+id/buttonAddArtist" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/spinnerGenres" android:text="Add" /> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/buttonAddArtist" android:padding="@dimen/activity_horizontal_margin" android:text="Artists" android:textAlignment="center" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/textView" android:text="Tap on an Artist to add and view tracks" android:textAlignment="center" /> <ListView android:id="@+id/listViewArtists" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textView1"></ListView> </RelativeLayout> |
- For ArtistsActivity we will create almost the same layout with little changes. So this activity will be like.
- For this activity you can again use the following 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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_artist" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="net.simplifiedcoding.firebasedatabaseexample.ArtistActivity"> <TextView android:id="@+id/textViewArtist" android:padding="@dimen/activity_horizontal_margin" android:textAlignment="center" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" android:textStyle="bold" android:layout_width="match_parent" android:layout_height="wrap_content" /> <EditText android:layout_below="@id/textViewArtist" android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter track name" /> <LinearLayout android:orientation="horizontal" android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/editTextName"> <SeekBar android:layout_weight="1" android:id="@+id/seekBarRating" android:layout_width="match_parent" android:layout_height="wrap_content" android:max="5"></SeekBar> <TextView android:text="1" android:id="@+id/textViewRating" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <Button android:id="@+id/buttonAddTrack" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/linearLayout" android:text="Add" /> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/buttonAddTrack" android:padding="@dimen/activity_horizontal_margin" android:text="Tracks" android:textAlignment="center" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <ListView android:id="@+id/listViewTracks" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textView"></ListView> </RelativeLayout> |
- Now lets save the data in Firebase. But before proceeding in save operation we need to define the Models for Artist and Track.
Defining Models
- Create a java class named Artist and write the following code.
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 |
package net.simplifiedcoding.firebasedatabaseexample; import com.google.firebase.database.IgnoreExtraProperties; /** * Created by Belal on 2/26/2017. */ @IgnoreExtraProperties public class Artist { private String artistId; private String artistName; private String artistGenre; public Artist(){ //this constructor is required } public Artist(String artistId, String artistName, String artistGenre) { this.artistId = artistId; this.artistName = artistName; this.artistGenre = artistGenre; } public String getArtistId() { return artistId; } public String getArtistName() { return artistName; } public String getArtistGenre() { return artistGenre; } } |
- Now again create one more class named Track and write the following code.
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 |
package net.simplifiedcoding.firebasedatabaseexample; import com.google.firebase.database.IgnoreExtraProperties; /** * Created by Belal on 2/26/2017. */ @IgnoreExtraProperties public class Track { private String id; private String trackName; private int rating; public Track() { } public Track(String id, String trackName, int rating) { this.trackName = trackName; this.rating = rating; this.id = id; } public String getTrackName() { return trackName; } public int getRating() { return rating; } } |
- Now lets save an artist to the database.
Saving an Artist
- Come inside MainActivity.java and write the following code.
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 |
package net.simplifiedcoding.firebasedatabaseexample; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { //we will use these constants later to pass the artist name and id to another activity public static final String ARTIST_NAME = "net.simplifiedcoding.firebasedatabaseexample.artistname"; public static final String ARTIST_ID = "net.simplifiedcoding.firebasedatabaseexample.artistid"; //view objects EditText editTextName; Spinner spinnerGenre; Button buttonAddArtist; ListView listViewArtists; //a list to store all the artist from firebase database List<Artist> artists; //our database reference object DatabaseReference databaseArtists; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //getting the reference of artists node databaseArtists = FirebaseDatabase.getInstance().getReference("artists"); //getting views editTextName = (EditText) findViewById(R.id.editTextName); spinnerGenre = (Spinner) findViewById(R.id.spinnerGenres); listViewArtists = (ListView) findViewById(R.id.listViewArtists); buttonAddArtist = (Button) findViewById(R.id.buttonAddArtist); //list to store artists artists = new ArrayList<>(); //adding an onclicklistener to button buttonAddArtist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //calling the method addArtist() //the method is defined below //this method is actually performing the write operation addArtist(); } }); } /* * This method is saving a new artist to the * Firebase Realtime Database * */ private void addArtist() { //getting the values to save String name = editTextName.getText().toString().trim(); String genre = spinnerGenre.getSelectedItem().toString(); //checking if the value is provided if (!TextUtils.isEmpty(name)) { //getting a unique id using push().getKey() method //it will create a unique id and we will use it as the Primary Key for our Artist String id = databaseArtists.push().getKey(); //creating an Artist Object Artist artist = new Artist(id, name, genre); //Saving the Artist databaseArtists.child(id).setValue(artist); //setting edittext to blank again editTextName.setText(""); //displaying a success toast Toast.makeText(this, "Artist added", Toast.LENGTH_LONG).show(); } else { //if the value is not given displaying a toast Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show(); } } } |
- Now try running the application.
- The toast is fine now lets check the database.
- So we the artist is getting save. Everytime you will save an artist a new child node inside artists will be created with a unique id.
Retrieving Artists
- Now we will fetch all the artists. We already have the ListView to display all the artists with genre. But before proceeding in retrieving the artists in ListView we will create a Layout File and a Custom Adapter for the list.
- So first create a new layout file named layout_artist_list.xml it will contain two TextView.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:text="Atif Aslam" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" android:id="@+id/textViewName" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:text="Rock" android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" android:id="@+id/textViewGenre" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> |
- Now create one more class named ArtistList and write the following code.
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 |
package net.simplifiedcoding.firebasedatabaseexample; import android.app.Activity; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; /** * Created by Belal on 2/26/2017. */ public class ArtistList extends ArrayAdapter<Artist> { private Activity context; List<Artist> artists; public ArtistList(Activity context, List<Artist> artists) { super(context, R.layout.layout_artist_list, artists); this.context = context; this.artists = artists; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View listViewItem = inflater.inflate(R.layout.layout_artist_list, null, true); TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName); TextView textViewGenre = (TextView) listViewItem.findViewById(R.id.textViewGenre); Artist artist = artists.get(position); textViewName.setText(artist.getArtistName()); textViewGenre.setText(artist.getArtistGenre()); return listViewItem; } } |
- Now lets retrieve all the artists. For this we will attach a ValueEventListener to the database reference object, inside onStart() method of MainActivity.
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 |
@Override protected void onStart() { super.onStart(); //attaching value event listener databaseArtists.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { //clearing the previous artist list artists.clear(); //iterating through all the nodes for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { //getting artist Artist artist = postSnapshot.getValue(Artist.class); //adding artist to the list artists.add(artist); } //creating adapter ArtistList artistAdapter = new ArtistList(MainActivity.this, artists); //attaching adapter to the listview listViewArtists.setAdapter(artistAdapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); } |
- Now again run the application.
- So the Artists are getting fetched. Also if you will add new Artist it will be automatically added inside the ListView as the method onDataChange() will be executed on any data change.
- Now we will add Tracks to a particular Artist. For this we will open a new Activity when an Artist is selected from the ListView. For this we have to attach an OnItemClickListener to the ListView.
- So add the following code inside onCreate() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//attaching listener to listview listViewArtists.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { //getting the selected artist Artist artist = artists.get(i); //creating an intent Intent intent = new Intent(getApplicationContext(), ArtistActivity.class); //putting artist name and id to intent intent.putExtra(ARTIST_ID, artist.getArtistId()); intent.putExtra(ARTIST_NAME, artist.getArtistName()); //starting the activity with intent startActivity(intent); } }); |
- Now run your application and select an Artist from the List. A new activity will open displaying the artist name.
- Now lets proceed in adding and retrieving tracks. But before we need to create one more class for the adapter of Track List.
- So create a new class named TrackList and write the following code.
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 |
package net.simplifiedcoding.firebasedatabaseexample; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; /** * Created by Belal on 2/26/2017. */ public class TrackList extends ArrayAdapter<Track> { private Activity context; List<Track> tracks; public TrackList(Activity context, List<Track> tracks) { super(context, R.layout.layout_artist_list, tracks); this.context = context; this.tracks = tracks; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View listViewItem = inflater.inflate(R.layout.layout_artist_list, null, true); TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName); TextView textViewRating = (TextView) listViewItem.findViewById(R.id.textViewGenre); Track track = tracks.get(position); textViewName.setText(track.getTrackName()); textViewRating.setText(String.valueOf(track.getRating())); return listViewItem; } } |
- Now lets add and retrieve tracks.
Adding and Retrieving Tracks from Firebase Realtime Database
- Come inside ArtistActivity.java and write the following code. The process is same as we did above that is why I am not explaining the codes with comments.
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 |
package net.simplifiedcoding.firebasedatabaseexample; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; public class ArtistActivity extends AppCompatActivity { Button buttonAddTrack; EditText editTextTrackName; SeekBar seekBarRating; TextView textViewRating, textViewArtist; ListView listViewTracks; DatabaseReference databaseTracks; List<Track> tracks; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_artist); Intent intent = getIntent(); /* * this line is important * this time we are not getting the reference of a direct node * but inside the node track we are creating a new child with the artist id * and inside that node we will store all the tracks with unique ids * */ databaseTracks = FirebaseDatabase.getInstance().getReference("tracks").child(intent.getStringExtra(MainActivity.ARTIST_ID)); buttonAddTrack = (Button) findViewById(R.id.buttonAddTrack); editTextTrackName = (EditText) findViewById(R.id.editTextName); seekBarRating = (SeekBar) findViewById(R.id.seekBarRating); textViewRating = (TextView) findViewById(R.id.textViewRating); textViewArtist = (TextView) findViewById(R.id.textViewArtist); listViewTracks = (ListView) findViewById(R.id.listViewTracks); tracks = new ArrayList<>(); textViewArtist.setText(intent.getStringExtra(MainActivity.ARTIST_NAME)); seekBarRating.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { textViewRating.setText(String.valueOf(i)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); buttonAddTrack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { saveTrack(); } }); } @Override protected void onStart() { super.onStart(); databaseTracks.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { tracks.clear(); for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { Track track = postSnapshot.getValue(Track.class); tracks.add(track); } TrackList trackListAdapter = new TrackList(ArtistActivity.this, tracks); listViewTracks.setAdapter(trackListAdapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void saveTrack() { String trackName = editTextTrackName.getText().toString().trim(); int rating = seekBarRating.getProgress(); if (!TextUtils.isEmpty(trackName)) { String id = databaseTracks.push().getKey(); Track track = new Track(id, trackName, rating); databaseTracks.child(id).setValue(track); Toast.makeText(this, "Track saved", Toast.LENGTH_LONG).show(); editTextTrackName.setText(""); } else { Toast.makeText(this, "Please enter track name", Toast.LENGTH_LONG).show(); } } } |
- Again run your application and try adding tracks.
- As you can see tracks are getting saved. Now lets see updating the Artist.
Updating Artist in Firebase Database
- For updating an existing artist name or genre we will show a Dialog to enter new detail. Dialog will be opened on long pressing an Artist from the list.
- So first create a new layout file named update_dialog.xml and write the following xml code. The same dialog will be used for deleting the artist as well.
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 |
<?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="match_parent" android:orientation="vertical" android:padding="@dimen/activity_horizontal_margin"> <EditText android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter name" /> <Spinner android:id="@+id/spinnerGenres" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/editTextName" android:entries="@array/genres"></Spinner> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/buttonUpdateArtist" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Update" /> <Button android:id="@+id/buttonDeleteArtist" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Delete" /> </LinearLayout> </LinearLayout> |
- As you can see we have two buttons one to update the artist and other one to delete the artist.
- Now come inside MainActivity.java and define a method updateArtist().
1 2 3 4 5 6 7 8 9 10 11 12 |
private boolean updateArtist(String id, String name, String genre) { //getting the specified artist reference DatabaseReference dR = FirebaseDatabase.getInstance().getReference("artists").child(id); //updating artist Artist artist = new Artist(id, name, genre); dR.setValue(artist); Toast.makeText(getApplicationContext(), "Artist Updated", Toast.LENGTH_LONG).show(); return true; } |
- Define one more method named showUpdateDeleteDialog(). In this method we are building a Dialog and on update button click we are calling the above method updateArtist() to update the artist.
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 |
private void showUpdateDeleteDialog(final String artistId, String artistName) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); final View dialogView = inflater.inflate(R.layout.update_dialog, null); dialogBuilder.setView(dialogView); final EditText editTextName = (EditText) dialogView.findViewById(R.id.editTextName); final Spinner spinnerGenre = (Spinner) dialogView.findViewById(R.id.spinnerGenres); final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdateArtist); final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDeleteArtist); dialogBuilder.setTitle(artistName); final AlertDialog b = dialogBuilder.create(); b.show(); buttonUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String name = editTextName.getText().toString().trim(); String genre = spinnerGenre.getSelectedItem().toString(); if (!TextUtils.isEmpty(name)) { updateArtist(artistId, name, genre); b.dismiss(); } } }); buttonDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /* * we will code this method to delete the artist * */ } }); } |
- Now inside onCreate() attach an OnItemLongClickListener to the ListView. And on LongClick we will call the method showUpdateDeleteDialog().
1 2 3 4 5 6 7 8 9 10 |
listViewArtists.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) { Artist artist = artists.get(i); showUpdateDeleteDialog(artist.getArtistId(), artist.getArtistName()); return true; } }); |
- Now again try running the application. Long press on an Artist and try updating it.
- So the update is working fine. Now only the delete operation is remaining. So lets delete an Artist.
Deleting Artist from Firebase Realtime Database
- Remember when we delete an Artist all the tracks of that particular Artist should be deleted as well.
- So define a method deleteArtist() inside MainActivity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
private boolean deleteArtist(String id) { //getting the specified artist reference DatabaseReference dR = FirebaseDatabase.getInstance().getReference("artists").child(id); //removing artist dR.removeValue(); //getting the tracks reference for the specified artist DatabaseReference drTracks = FirebaseDatabase.getInstance().getReference("tracks").child(id); //removing all tracks drTracks.removeValue(); Toast.makeText(getApplicationContext(), "Artist Deleted", Toast.LENGTH_LONG).show(); return true; } |
- Now call this method inside Click Listener of Delete Artist Button which is inside showUpdateDeleteDialog().Â
1 2 3 4 5 6 7 8 9 10 |
buttonDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { deleteArtist(artistId); b.dismiss(); } }); |
- Now run your application and try deleting an Artist.
- Bingo! the delete is working fine as well. If you are having troubles about this Firebase Realtime Database Tutorial you can get my source code from below.
Firebase Realtime Database CRUD
So thats all for this Firebase Realtime Database tutorial. We covered all the operations like Creating, Reading, Updating and Deleting (CRUD) data in Firebase Realtime Database. If you are having any queries and confusions then lets discuss in comment section.