Part 1: CRUD Operation Using Android with Firebase Database
Let’s Start
Pre-Requirements
- Firebase Must be Connected With Your Android Application
- Add Below Firebase Database dependency to your app level build.gradle file. Android Studio Version is >3
implementation 'com.google.firebase:firebase-database:19.2.1'
3. Now Make Sure That You Allow Read and Write Permission True In Your Firebase Database.
For That Go to FirebaseConsole>Your Project>Database >Rules
Above Pre-Requirement is not done then follow my previous Tutorial it will Guide you in better way.
1. Insert Data On Firebase
Firebase Stored Data In Key-Value Pair , So we Have to Send Our Data into key-value Pair.
There are Two way For sending a Key-Value Pair Data to firebase
1. Directly Pass The Model Class ,here Is an Example For it.
Step 1: Create One Java Class and Define a Property That You Want to Store In Database .Here I am Creating a Rating Class inside the Model Folder .
public class Rating {
private String id;
private String comment;
private String ratestar;
public Rating(){//this constructor is required
}
public Rating(String id, String comment, String ratestar) {
this.id = id;
this.comment = comment;
this.ratestar = ratestar;
}
public String getId() {
return id;
}
public String getComment() {
return comment;
}
public String getRatestar() {
return ratestar;
}
}
Step 2: Open Main Activity. And Create a instance of a firebase Database.
Something Like this,
//our database reference object
DatabaseReference databaseRatings;
Step 3: Now , Inside the OnCreate Method we Intialize this Object and assign a Firebase Database Reference like this,
//getting the reference of rating node
databaseRatings = FirebaseDatabase.getInstance().getReference("ratingList");
Here, “ ratinglist ” is a Database tableName or RootNode name , Your All data will Store into Firebase Project inside this Rating List, see the below photo
Step 4 : Now Inside OnCreate add Your Submit Button click event Or Any Button Click Submit Your data to firebase . so Create a Onclick Method and Call a Insert Method.Here getRating is a button
private Button getRating;//inside oncreate methodgetRating.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
basicReadWrite();
}
});
Step 5: Now Create a method Outside Oncreate , that will Insert Your Data to firebase.
If you need any gradle file to add for this please add and import to your main activity
public void basicReadWrite() {
try {
final String comment = editText.getText().toString().trim();
final String star = String.valueOf(ratingBar.getRating());;
if (TextUtils.isEmpty(comment)) {
editText.setError(REQUIRED);
return;
}
Toast.makeText(this, "Posting...", Toast.LENGTH_SHORT).show();
//getting a unique id using push().getKey() method
String id = databaseRatings.push().getKey();
Rating rating=new Rating(id,comment,star);
//upload your class Property to Firebase database
databaseRatings.child(id).setValue(rating);
editText.setText("");//empty Edit text Value
Toast.makeText(this, "Review added", Toast.LENGTH_LONG).show();//displaying a success toast
}
catch (Exception ex) {
Log.d(TAG, "Value is: " + ex);
}
}
Here , id = it is generate a unique id all time and push this unique id to your database .
databaseRatings.child(id).setValue(rating);
This Line explained as that inside Your Firebase Database create a child node and it name is same as id we have passed here . and inside this id our class data is stored . see the picture of database For Better Understand.
Inside this Picture,
review-and-ratings : it is our Project Name Or Root Node name
ratingList : It is a Reference Name or Table Name . It is a child Node For Project
Id (-M37nyejKHQYMXnccjHP) : It is a child Node For ratingList
2. Using Hashmap (Send Value Manually Using put method)
Step 1: Here We Create a User Class Inside Your Model Folder , Same as above
package com.example.firebaseauthentication.Model;
import java.util.HashMap;
public class User {
public String UserId;
public String UserName;
public String Email;
public String Password;
private HashMap<String, String> dataMap = new HashMap<String, String>();
public User() {
/*Default constructor required for calls DataSnapshot.getValue(User.class)*/
}
public User(String UserId,String UserName, String Email,String Password) {
this.UserId = UserId;
this.UserName = UserName;
this.Email = Email;
this.Password=Password;
}
public HashMap<String, String> fireebaseMap(){
return dataMap;
}
}
You just compare Method 1 class and method 2 model class Here is some differnce .
Now All the Steps are Same as Method 1 , just change inside BasicReadwrite method is here,
public void basicReadWrite() {
try {
final String userName=inputusername.getText().toString().trim();
final String email = inputEmail.getText().toString().trim();
final String password = inputPassword.getText().toString().trim();
/* Here write Code for that username email and password is not empty */
mDatabase = FirebaseDatabase.getInstance().getReference();
User obj = new User();
HashMap<String, String> dataMap = obj.fireebaseMap();
dataMap.put("UserId",userKey);
dataMap.put("UserName", userName);
dataMap.put("Email", email);
dataMap.put("Password", password);
mDatabase.child("RegisterUser").push().setValue(dataMap);
}
catch (Exception ex) {
Log.d(TAG, "Value is: " + ex);
}
}
Here We sending Our Data in key And value Pair ,
Explanation Of Above Code
1.We Create a HashMap Object And access with the User obj ,
User obj = new User();
HashMap<String, String> dataMap = obj.fireebaseMap();
2.Now Put key-value Pair using Hashmap. Here , left side is a Key and right side is a value.
dataMap.put("UserId",userKey);
dataMap.put("UserName", userName);
dataMap.put("Email", email);
dataMap.put("Password", password);
3. Now Push Value to Firebase Database,
mDatabase.child("RegisterUser").push().setValue(dataMap);
Here Is a Picture That How data stored inside firebase database,
So You Can Better Understand the code of Insert.
Thanks ,
IF Any Query then Contact Directly to My Linkedin, Or Comment me.Or Contact This Website ,