- Mastering Firebase for Android Development
- Ashok Kumar S
- 752字
- 2021-06-18 18:49:14
Logic
The following POJO class expresses the idea and the data format that we will save in Firebase. Using the POJO class we will pass the data to the adapter:
package com.ashok.packt.realtime.database.model;
/**
* Created by ashok.kumar on 20/10/17.
*/
public class Donor {
private String FullName;
private String Email;
private String City;
private String BloodGroup;
public Donor(){
}
Now within the same class lets create a constructor for passing the data to the POJO:
public Donor(String fullName, String email, String city, String bloodGroup) {
FullName = fullName;
Email = email;
City = city;
BloodGroup = bloodGroup;
}
public String getFullName() {
return FullName;
}
public void setFullName(String fullName) {
FullName = fullName;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getBloodGroup() {
return BloodGroup;
}
public void setBloodGroup(String bloodGroup) {
BloodGroup = bloodGroup;
}
}
Now let's write our Adapter class. The Adapter class requires POJO, view holder, and row layout. Consider spending some time on understanding the RecyclerView adapter:
package com.ashok.packt.realtime.database.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ashok.packt.realtime.database.R;
import com.ashok.packt.realtime.database.model.Donor;
import java.util.List;
/**
* Created by ashok.kumar on 20/05/18.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.View_Holder>{
private Context mContext;
private List<Donor> ItemList;
public RecyclerViewAdapter(Context mContext, List<Donor> itemList) {
this.mContext = mContext;
ItemList = itemList;
}
The constructors require context and the list of donor object for setting the data in RecyclerView callbacks.
@Override
public View_Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.donor_list_row, parent, false);
return new View_Holder(itemView);
}
The above Override method will be responsible for inflating the donor list item row.
@Override
public void onBindViewHolder(View_Holder holder, int position) {
Donor Item = ItemList.get(position);
holder.Name.setText(Item.getFullName());
holder.City.setText(Item.getCity());
holder.BloodGroup.setText(Item.getBloodGroup());
holder.Email.setText(Item.getEmail());
}
@Override
public int getItemCount() {
return ItemList.size();
}
public class View_Holder extends RecyclerView.ViewHolder {
TextView Name;
TextView City;
TextView BloodGroup;
TextView Phone;
TextView Email;
View_Holder(View itemView) {
super(itemView);
Name = (TextView) itemView.findViewById(R.id.donorName);
City = (TextView) itemView.findViewById(R.id.donorCity);
BloodGroup = (TextView) itemView.findViewById(R.id.donorBloodGroup);
Email = (TextView) itemView.findViewById(R.id.donorEmail);
}
}
}
Now, MainActivity holds the complete logic for the application by adding the data to Firebase, fetching the data from Firebase, and loading that in RecyclerView. I have also written methods to update, find, and delete for your future reference:
package com.ashok.packt.realtime.database;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.ashok.packt.realtime.database.adapter.RecyclerViewAdapter;
import com.ashok.packt.realtime.database.model.Donor;
import com.google.firebase.database.ChildEventListener;
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.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private DatabaseReference myDatabaseReference;
private String personId;
private List<Donor> ItemList;
private RecyclerView mRecyclerview;
private RecyclerViewAdapter mAdapter;
Lets initialise all the above code in the onCreate method as shown below:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerview = (RecyclerView) findViewById(R.id.peopleList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
mRecyclerview.setLayoutManager(mLayoutManager);
// for data persistence
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
myDatabaseReference=FirebaseDatabase.getInstance().getReference("Donor");
personId= myDatabaseReference.push().getKey();
(findViewById(R.id.addBtn)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String FullName = ((EditText)findViewById(R.id.donorNameInput)).getText().toString();
String Email = ((EditText)findViewById(R.id.donorEmailInput)).getText().toString();
String City = ((EditText)findViewById(R.id.donorCityInput)).getText().toString();
String BloodGroup = ((EditText)findViewById(R.id.donorBloodGroupInput)).getText().toString();
addPerson(FullName,Email, City, BloodGroup);
}
});
(findViewById(R.id.loadBtn)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
readData();
}
});
}
After adding the views its now time to work on the adding and retrieving the data as shown below:
private void addPerson(String name, String Email, String city, String Bloodgroup){
personId= myDatabaseReference.push().getKey();
Donor person = new Donor(name, Email, city, Bloodgroup);
myDatabaseReference.child(personId).setValue(person);
}
private void updatePerson(String name,int phoneNumber){
myDatabaseReference.child(personId).child("fullName").setValue(name);
myDatabaseReference.child(personId).child("phoneNumber").setValue(phoneNumber);
}
private void removePerson(String name){
myDatabaseReference.child(personId).removeValue();
}
private void readData(){
ItemList = new ArrayList<>();
myDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> snapshotIterator = dataSnapshot.getChildren();
Iterator<DataSnapshot> iterator = snapshotIterator.iterator();
while((iterator.hasNext())){
Donor donor = iterator.next().getValue(Donor.class);
ItemList.add(donor);
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mAdapter = new RecyclerViewAdapter(this, ItemList);
mRecyclerview.setAdapter(mAdapter);
}
We also can do the specific person search as shown below:
private void findPerson(String name){
Query deleteQuery = myDatabaseReference.orderByChild("fullName").equalTo(name);
deleteQuery.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Iterable<DataSnapshot> snapshotIterator = dataSnapshot.getChildren();
Iterator<DataSnapshot> iterator = snapshotIterator.iterator();
while((iterator.hasNext())){
Log.d("Item found: ",iterator.next().getValue().toString()+"---");
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Item not found: ","this item is not in the list");
}
});
}
}
When you compile and run the program in your Android device the output will have the following look and feel: