Upload and Retrieve Data in Firebase in Cardview

Android Firebase Realtime Database with RecyclerView Tutorial

In this slice we want to look at several RecyclerView and Firebase Realtime database examples. Basically how to perform several Grime operations like adding, retrieving and showing in recyclerview.

What Is Firebase Realtime Database?

Firebase Realtime Database is i of the services provided Firebase Platform which is endemic by Google.

Basically it's what we call a Database BAAS, or a Database Backend As A Service. Information technology's hosted in the Cloud.

Why Firebase Realtime Database?

It differs from many databases you may already know in the many ways. These ways are what gives Firebase Realtime Database it's advantages.

  1. It's hosted in the Deject while the others similar SQLite and Realm are hosted locally. This makes Firebase Realtime Database to be accessible to many apps. Databases like SQLite and Realm are localised within a unmarried app. Firebase Realtime Database is accessible to many applications.
  2. It is Realtime. This is the biggest difference. That ways y'all save data and automatically the data in all continued apps get updated instantly. This makes information technology quite applicable to many types of apps like chat and messaging apps, apps that require instant synchronization.
  3. Information technology stores information in json format unlike tables in sqlite. This makes Firebase Realtime Database quite scalable.
  4. It has both Free and Paid plans. This is the best case scenarion since and then you can utilize information technology for both learning and commercial purposes.

What is RecyclerView

RecyclerView is an android adapterview that allows us return large data sets efficiently. Normally to return lists information in android you need an adapterview and an adapter. The adapterview is the list widget and examples include ListView, Gridview, Spinner and of form RecyclerView.

Then the adapter is normally responsible for connecting the adapterview to the data source. And in fact y'all commonly can utilize custom layouts to present a unmarried list item. That layout is as well inflated inside the adapter.

Read more about the RecyclerView here.

Why RecyclerView?

Well we've said several adapterviews can be used for information presentation in android. There is ListView, GridView, Spinner etc. ListView used to be the about popular until the introduction of RecyclerView.

These days recyclerview is the most unremarkably used adapterview due to it'south flexibility and functioning. RecyclerView can exist used to build nearly whatsoever blazon of view, from a list view, to a grid/staggered view, to a table view, to a calender etc.

This fact it makes information technology quite special and usable in many scenarios. Yet fifty-fifty it'due south not much more difficult than the other adapterviews.

Tools Used

This example was written with the following tools:

  • Microsoft Windows eight.1 – This is my operating system.
  • Android Studio – This is my IDE(Integerated Develpment Kit) past Jetbrains and Google.
  • Genymotion Emulator – This we utilize to test our appilcations.
  • Language : Java – Java is the most pop programming language.

one. Android Firebase => Simple RecyclerView – Salve,Retrieve then Evidence

[center]Android Firebase Realtime Database recyclerView Tutorial[/middle]

This is an android firebase RecyclerView tutorial. How to save data to firebase,recollect then prove that data in a unproblematic Recyclerview. We just apply a single fields of data.

General Concepts You Learn From this Case.

Here are some of the concepts you can learn from this tutorial:

  • What is Firebase and What is RecyclerView and Why use them.
  • How to Save data from edittext to google Firebase Realtime Database.
  • How to Get or Retriev or Read Data From Firebase Database by attaching events to a DatabaseReference case then populating a coffee arraylist
  • How to Demark the data retrieved to an instance of RecyclerView.Adapter bracket.
  • How to create and operate on database in Firebase.
  • Firebase example apps with recyclerview.
  • Firebase Database Synchronization

Specific Concepts Yous volition Acquire

  • How to utilize Firebase Database Reference.
  • How to add child to Firebase Database Reference

Demo

Hither's the projection demo for this tutorial:

Setup and Configuration

(a). Create Basic Activity Project
  1. First create a new project in android studio.
(b). Create Firebase and Download Configuration File

Head over to Firebase Console, create a Firebase App, Annals your app id and download the google-services.json file. Add information technology to your app folder.

(c). Specify Maven repository URL

Caput over to project level(project folder) build.gradle and

  1. Add Google services classpath every bit below
  2. Add maven repository url
          // Acme-level build file where you can add together configuration options common to all sub-projects/modules.  buildscript {     repositories {         jcenter()     }     dependencies {         classpath 'com.android.tools.build:gradle:2.3.iii'         classpath 'com.google.gms:google-services:three.1.0'          // Annotation: Do non identify your application dependencies hither; they belong         // in the individual module build.gradle files     } }  allprojects {     repositories {         jcenter()         maven {             url "https://maven.google.com" // Google's Maven repository         }     } }  task clean(type: Delete) {     delete rootProject.buildDir }        

This volition allow the states to fetch our Firebase from maven.google com. Firebase is a 3rd party library and has to be downloaded for us to apply it in our projection.

(d). Add Firebase Dependencies

Add them in yous app level(app folder) build.gradle nosotros need to add several dependencies. Nosotros have added back up libraries like appcompat, design and cardview. AppCompat will give us AppCompatActivity, the course from which our MainActivity will be deriving. We add them using the implementation statement.

The design support volition give u.s.a. the recyclerveiew which is our list widget. It'southward what we will be populating with data nosotros query from our Firebase. The cardview on the other mitt will permit us piece of work with cardviews as our item views. The recyclerview shall comprise cardviews.

Then the we've added the Firebase Core as well equally Firebase Database. Firebase remember is a platform while the Firebase Database is the database we store our data. You may use later versions. Nevertheless don't forget to apply the google services every bit nosotros've done.

          dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])      testImplementation 'junit:junit:four.12'     implementation 'com.android.support:appcompat-v7:23.3.0'     implementation 'com.android.support:design:23.three.0'     implementation 'com.android.support:cardview-v7:23.3.0'      implementation 'com.google.firebase:firebase-core:11.8.0'     implementation 'com.google.firebase:firebase-database:11.8.0' } utilize plugin: 'com.google.gms.google-services'                  

Make sure yous employ plugin: 'com.google.gms.google-services' as above.

2. Our Java Code

We write this example using Java Programming Language. So nosotros'll decouple various parts of our app into several classes.

(a). Our Model Class
  • Is our Data Object class
  • Must Take an empty constructor.
  • You tin can create,laissez passer data to and use other constructors

Equally model or data objexct class basically represents a grade that volition model our data. When you lot are working with any form of data, it's e'er a good thought to stand for the data in a concrete uncomplicated class. The object of that class tin then be queried around as needed. Normally these types of classes take what we phone call accessor methods. Those methods are always public hence providing a manner to betrayal the properties of the class, which are e'er private.

In our case we've created a course called Spacecraft. That course, will have a single property, just a name to hold the proper noun for that spacecraft. Then nosotros provide our class with a public default constructor. This is a characteristic normally needed by database engines that rely on reading the data object to automatically generate the database schema. Firebase Database definitely does that just as Realm, a local database for java and android.

Then we provide our class with a getName and setName accessor methods.

          package com.tutorials.hp.firebasesimplerecyclerview.m_Model;  public course Spacecraft {      String proper noun;      //EMPTY CONSTR     public Spacecraft() {     }      public String getName() {         return name;     }      public void setName(Cord proper name) {         this.name = proper name;     } }        
(b). Our FirebaseHelper Grade
  • Basically,our Grime class.
  • Hither we perform reads and writes to Firebase database.
  • To persist data we use setValue().
  • Prior to calling setValue() method,we phone call push() to ensure nosotros append data to database,not replace.
  • We make full a simple arraylist.

We have created this course, FirebaseHelper class to to allow us salve as well as query or read data from Firebase. Nosotros starting time past defining the package to host our class. So add our imports including several classes from com.google.firebase.database.

We have defined several case fields including:

  1. DatabaseReference — Our database reference.
  2. Boolean value – to determine if nosotros've successfully saved or non.
  3. ArrayList – To hold our data fetched from Firebase.

We beginning by receiving a Database Reference via the constructor. We then assign the database reference to the local instance field we had maintained.

Saving Information To FirebaseDatabase

We and then define a method to relieve data to Firebase Database. That method volition receive a Spacecraft object as a parameter. Given we are receiving the Spacecraft object from the exterior world, information technology woudld be ideal to first check it out for cipher.

To salve data to Firebase

                      db.kid("Spacecraft").button().setValue(spacecraft);        

In that instance db is our DatabaseReference. We obtain it's child node via the child() method. And so pass the proper noun of our "table". And then nosotros use the push() method to push information to Firebase. All the same we have to set the value that we are pushing. We employ the setValue method to set our spacecraft object. And that's how nosotros salve information to our Firebase Database. Note that we have used a endeavor catch cake to catch a DatabaseException.

Retrieving Information From Firebase Database

We will receive data from Firebase Realtime Database and populate an ArrayList. And then afterward that ArrayList volition used as the data source for our recyclerview adapter.

To read data from firebase, nosotros demand to attach a ChildEventListener to our database reference. That will and so listen to changes in the data nodes. For example when a child node is added, modified, removed, or cancelled, we get callback methods containing our data snapshot. Nosotros can then read data from those data snapshots.

Then from each iteration you can invoke the getValue method of the data snapshot child to obtain the object.
Reading information from a DataSnapshot object is piece of cake. Yous simply loop through it'south children:

                      for (DataSnapshot ds : dataSnapshot.getChildren())         {             String name=ds.getValue(Spacecraft.class).getName();             spacecrafts.add(proper noun);         }        

Hither's the full code:

          package com.tutorials.hp.firebasesimplerecyclerview.m_FireBase;  import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseException; import com.google.firebase.database.DatabaseReference; import com.tutorials.hp.firebasesimplerecyclerview.m_Model.Spacecraft;  import java.util.ArrayList;  public class FirebaseHelper {      DatabaseReference db;     Boolean saved=aught;     ArrayList<String> spacecrafts=new ArrayList<>();      public FirebaseHelper(DatabaseReference db) {         this.db = db;     }      //Relieve     public Boolean save(Spacecraft spacecraft)     {         if(spacecraft==null)         {             saved=false;         }else {              try             {                 db.child("Spacecraft").push().setValue(spacecraft);                 saved=true;             }catch (DatabaseException e)             {                 east.printStackTrace();                 saved=false;             }          }          render saved;     }      //READ     public ArrayList<String> retrieve()     {         db.addChildEventListener(new ChildEventListener() {             @Override             public void onChildAdded(DataSnapshot dataSnapshot, String s) {                 fetchData(dataSnapshot);             }              @Override             public void onChildChanged(DataSnapshot dataSnapshot, Cord s) {                 fetchData(dataSnapshot);              }              @Override             public void onChildRemoved(DataSnapshot dataSnapshot) {              }              @Override             public void onChildMoved(DataSnapshot dataSnapshot, String s) {              }              @Override             public void onCancelled(DatabaseError databaseError) {              }         });          return spacecrafts;     }      private void fetchData(DataSnapshot dataSnapshot)     {         spacecrafts.clear();         for (DataSnapshot ds : dataSnapshot.getChildren())         {             String proper noun=ds.getValue(Spacecraft.class).getName();             spacecrafts.add together(name);         }     }  }        
(c). Our MyViewHolder course
  • Yeah,its our viewholder form.
  • Holds views for use prepare for recycling
          package com.tutorials.hp.firebasesimplerecyclerview.m_UI;  import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView;  import com.tutorials.hp.firebasesimplerecyclerview.R;  public class MyViewHolder extends RecyclerView.ViewHolder  {      TextView nameTxt;      public MyViewHolder(View itemView) {         super(itemView);          nameTxt=(TextView) itemView.findViewById(R.id.nameTxt);     } }        

That MyViewHolder is our ViewHolder class. These ever needed for the sake of recycling of views past the recyclerview. However to plow a form into a recyclerview viewholder we accept to derive from Recyclerview.ViewHolder form as you've seen higher up. Nosotros had started by imprortng several classes including the RecyclerView itself.

In our grade we've maintained a TextView called nameTxt. Then our MyViewHolder contstructorhas taken a View object. That View object has then been passed over to the super class which is the Recyclerview.ViewHolder.

And so we've referenced the nameTxt from its layout specification.

ix. Our MyAdapter class
  • Responsible for Layout Inflation.
  • Besides for data binding to views.
          bundle com.tutorials.hp.firebasesimplerecyclerview.m_UI;  import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;  import com.tutorials.hp.firebasesimplerecyclerview.R;  import java.util.ArrayList;  public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {      Context c;     ArrayList<String> spacecrafts;      public MyAdapter(Context c, ArrayList<String> spacecrafts) {         this.c = c;         this.spacecrafts = spacecrafts;     }      @Override     public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {         View v=LayoutInflater.from(c).inflate(R.layout.model,parent,imitation);         return new MyViewHolder(v);     }      @Override     public void onBindViewHolder(MyViewHolder holder, int position) {         holder.nameTxt.setText(spacecrafts.get(position));      }      @Override     public int getItemCount() {         render spacecrafts.size();     } }        

Adapters are important in the way android works with collection of information. Mobile devices be it HTC, Samsung, F7, Apple iOS, Infinix etc, all of them all heavily apps that need to render lists of information. That is just past nature of mobile devices. The screen is always tiny and therefore it'south appropriate to brandish items that can exist scrolled.

And RecyclerView is the number one adapterview for displaying large data sets. These data sets may come from the cloud similar Firebase. And in fact our information in this case is coming from Firebase Realtime database. So we've populated an ArrayList so far with the data we have already collected. Now it's time to demark that data. However that needs an Adapter.

Adapters:

  1. Allow us Bind data to our adapterviews.
  2. Help u.s. in inflating custom layouts into views so that we pattern custom adapterviews.

You make a recyclerview adapter past deriving from RecyclerView.Adapter<MyViewHolder>. The generic parameter is the ViewHolder. Deriving from that form will force us to override three methods:

  1. getItemCount – To return the number of items to be rendered in the recyclerview.
  2. onCreateViewHolder – This is where the inflation occurs. We useLayoutInflater for the inflation.
  3. onBindViewHolder – This is where we bind data to the widgets nosotros divers in the ViewHolder class.

Meanwhile our constructor has taken a Context object equally well equally the arraylist of our information.

(d). Our MainActivity
  • Launcher activity.
  • Reference RecyclerView and sets its layoutManager as well as its adapter.
  • Shows Input Dialog on FAB push button click.
  • Sets up our Firebase's by initializeing the DatabaseReference.
          package com.tutorials.hp.firebasesimplerecyclerview;  import android.app.Dialog; import android.os.Bundle; import android.back up.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.back up.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Push button; import android.widget.EditText; import android.widget.Toast;  import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.tutorials.hp.firebasesimplerecyclerview.m_FireBase.FirebaseHelper; import com.tutorials.hp.firebasesimplerecyclerview.m_Model.Spacecraft; import com.tutorials.hp.firebasesimplerecyclerview.m_UI.MyAdapter;  public course MainActivity extends AppCompatActivity {      DatabaseReference db;     FirebaseHelper helper;     RecyclerView rv;     EditText nameEditTxt;     MyAdapter adapter;      @Override     protected void onCreate(Packet savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);         setSupportActionBar(toolbar);          //SETUP RV         rv= (RecyclerView) findViewById(R.id.rv);         rv.setLayoutManager(new LinearLayoutManager(this));          //SETUP FB         db=FirebaseDatabase.getInstance().getReference();         helper=new FirebaseHelper(db);          //ADAPTER         adapter=new MyAdapter(this,helper.retrieve());         rv.setAdapter(adapter);          FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);         fab.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                   displayInputDialog();             }         });     }      private void displayInputDialog()     {         Dialog d=new Dialog(this);         d.setTitle("Save To Firebase");         d.setContentView(R.layout.input_dialog);          nameEditTxt= (EditText) d.findViewById(R.id.nameEditText);         Button saveBtn= (Push) d.findViewById(R.id.saveBtn);          //Salvage         saveBtn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                  //Get DATA                 String name=nameEditTxt.getText().toString();                  //Gear up DATA                 Spacecraft s=new Spacecraft();                 s.setName(proper noun);                  //VALIDATE                 if(name.length()>0 && proper name != nix)                 {                     if(helper.relieve(s))                     {                         nameEditTxt.setText("");                          adapter=new MyAdapter(MainActivity.this,helper.retrieve());                         rv.setAdapter(adapter);                     }                 }else                 {                     Toast.makeText(MainActivity.this, "Name Cannot Be Empty", Toast.LENGTH_SHORT).prove();                 }             }         });          d.bear witness();     }  }        

11. Our Layouts

(a). activity_main.xml

This is our main activity layout.

          <?xml version="1.0" encoding="utf-viii"?> <android.support.design.widget.CoordinatorLayout      android_layout_width="match_parent"     android_layout_height="match_parent"     android_fitsSystemWindows="true"     tools_context="com.tutorials.hp.firebasesimplerecyclerview.MainActivity">      <android.back up.design.widget.AppBarLayout         android_layout_width="match_parent"         android_layout_height="wrap_content"         android_theme="@style/AppTheme.AppBarOverlay">          <android.back up.v7.widget.Toolbar             android_id="@+id/toolbar"             android_layout_width="match_parent"             android_layout_height="?attr/actionBarSize"             android_background="?attr/colorPrimary"             app_popupTheme="@way/AppTheme.PopupOverlay" />      </android.back up.blueprint.widget.AppBarLayout>      <include layout="@layout/content_main" />      <android.support.design.widget.FloatingActionButton         android_id="@+id/fab"         android_layout_width="wrap_content"         android_layout_height="wrap_content"         android_layout_gravity="bottom|end"         android_layout_margin="@dimen/fab_margin"         android_src="@android:drawable/ic_dialog_email" />  </android.support.design.widget.CoordinatorLayout>                  
(b). content_main.xml

This is where we add our adapterview in this case a recyclerview.

          <?xml version="ane.0" encoding="utf-8"?> <RelativeLayout      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"     app_layout_behavior="@string/appbar_scrolling_view_behavior"     tools_context="com.tutorials.hp.firebasesimplerecyclerview.MainActivity"     tools_showIn="@layout/activity_main">      <android.support.v7.widget.RecyclerView         android_id="@+id/rv"         android_layout_width="match_parent"         android_layout_height="wrap_content"          /> </RelativeLayout>                  
(c). input_dialog.xml
  • defines our input dialogs layout
          <?xml version="i.0" encoding="utf-8"?> <LinearLayout     android_orientation="vertical" android_layout_width="match_parent"     android_layout_height="match_parent">      <LinearLayout         android_layout_width="fill_parent"         android_layout_height="match_parent"         android_layout_marginTop="?attr/actionBarSize"         android_orientation="vertical"         android_paddingLeft="15dp"         android_paddingRight="15dp"         android_paddingTop="10dp">          <android.support.blueprint.widget.TextInputLayout             android_id="@+id/nameLayout"             android_layout_width="match_parent"             android_layout_height="wrap_content">              <EditText                 android_id="@+id/nameEditText"                 android_layout_width="match_parent"                 android_layout_height="wrap_content"                 android_singleLine="true"                 android_hint= "Name" />         </android.back up.design.widget.TextInputLayout>          <Button android_id="@+id/saveBtn"             android_layout_width="fill_parent"             android_layout_height="wrap_content"             android_text="Salvage"             android_clickable="true"             android_background="@color/colorAccent"             android_layout_marginTop="10dp"             android_textColor="@android:color/white"/>      </LinearLayout>  </LinearLayout>        
(d). model.xml

This is our RecyclerView row model. This layout volition exist inflated in adapter grade.

          <?xml version="i.0" encoding="utf-8"?> <android.support.v7.widget.CardView     android_orientation="horizontal" android_layout_width="match_parent"      android_layout_margin="10dp"     card_view_cardCornerRadius="5dp"     card_view_cardElevation="5dp"     android_layout_height="200dp">          <LinearLayout             android_orientation="vertical"             android_layout_width="match_parent"             android_layout_height="match_parent">              <TextView                 android_layout_width="match_parent"                 android_layout_height="wrap_content"                 android_textAppearance="?android:attr/textAppearanceLarge"                 android_text="Proper name"                 android_id="@+id/nameTxt"                 android_padding="10dp"                 android_textColor="@color/colorAccent"                 android_textStyle="bold"                 android_layout_alignParentLeft="true"                 />      </LinearLayout>  </android.support.v7.widget.CardView>        
12. AndroidManifest.xml
  • Remember to add permission for internet in your manifest file.

<uses-permission android_name="android.permission.INTERNET"/>

Download
Resource Link
GitHub Browse Browse
GitHub Download Link Download

2. Android Firebase – RecyclerView Multiple Fields

Android Firebase Database RecyclerView Tutorial This is an android firebase database RecyclerView tutorial. How to save data to firebase,recall and so prove that data in a custom RecyclerView.

This time around we use multiple fields as opposed to unmarried field like nosotros did in the previous example.

1. Setting Upwards

(a). Create Basic Activity Project
  1. Kickoff create a new project in android studio. Go to File –> New Project.
(b).Create Firebase and Download Configuration File

Head over to Firebase Console, create a Firebase App, Register your app id and download the google-services.json file. Add it to your app folder.

(c). Specify Maven repository URL

Head over to project level(projection folder) build.gradle and

  1. Add Google services classpath as below
  2. Add maven repository url
          // Top-level build file where y'all tin can add together configuration options mutual to all sub-projects/modules.  buildscript {     repositories {         jcenter()     }     dependencies {         classpath 'com.android.tools.build:gradle:2.3.iii'         classpath 'com.google.gms:google-services:3.1.0'          // Annotation: Do not place your application dependencies here; they belong         // in the individual module build.gradle files     } }  allprojects {     repositories {         jcenter()         maven {             url "https://maven.google.com" // Google's Maven repository         }     } }  job clean(blazon: Delete) {     delete rootProject.buildDir }        
(d). Add Firebase Dependencies

Add them in you app level(app binder) build.gradle, then

          dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])      testCompile 'junit:junit:4.12'     compile 'com.android.support:appcompat-v7:23.3.0'     compile 'com.android.support:design:23.3.0'     compile 'com.android.support:cardview-v7:23.3.0'      compile 'com.google.firebase:firebase-core:11.8.0'     compile 'com.google.firebase:firebase-database:xi.8.0' } apply plugin: 'com.google.gms.google-services'                  

Make certain you apply plugin: 'com.google.gms.google-services' as above.

(e). AndroidManifest
  • Remember to add together permission for internet in your manifest file.
          <?xml version="1.0" encoding="utf-8"?> <manifest     packet="com.tutorials.hp.firebaserecyclermulti_items">      <uses-permission android_name="android.permission.Net"/>     .... </manifest>        

2. Classes

(a). Our Model Form
  • Is our Data Object class
  • Must Have an empty constructor.
  • You lot can create,laissez passer data to and utilise other constructors
          packet com.tutorials.hp.firebaserecyclermulti_items.m_Model;  /*  * 1. OUR MODEL Class  */ public class Spacecraft {     String name,propellant,description;      public Spacecraft() {     }      public String getName() {         return proper name;     }      public void setName(String name) {         this.proper noun = name;     }      public String getPropellant() {         render propellant;     }      public void setPropellant(Cord propellant) {         this.propellant = propellant;     }      public String getDescription() {         return description;     }      public void setDescription(String description) {         this.description = description;     } }                  
(b). Our FirebaseHelper Form
  • Basically,our Crud class.
  • Here we perform reads and writes to Firebase database.
  • To persist data we use setValue().
  • Prior to calling setValue() method,we call push() to ensure nosotros append data to database,not replace.
  • Nosotros fill up an arraylist with model objects.
          bundle com.tutorials.hp.firebaserecyclermulti_items.m_FireBase;  import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseException; import com.google.firebase.database.DatabaseReference; import com.tutorials.hp.firebaserecyclermulti_items.m_Model.Spacecraft;  import java.util.ArrayList;  /*  * 1. RECEIVE DB REFERENCE  * 2. Save  * iii. Recollect  * 4. RETURN ARRAYLIST  */ public class FirebaseHelper {     DatabaseReference db;     Boolean saved=cipher;     ArrayList<Spacecraft> spacecrafts=new ArrayList<>();      /*      PASS DATABASE REFRENCE      */     public FirebaseHelper(DatabaseReference db) {         this.db = db;     }      //WRITE IF Not Nothing     public Boolean save(Spacecraft spacecraft)     {         if(spacecraft==nil)         {             saved=false;          }else         {             effort             {                 db.kid("Spacecraft").push button().setValue(spacecraft);                 saved=truthful;              }take hold of (DatabaseException due east)             {                 east.printStackTrace();                 saved=simulated;             }         }          render saved;     }      //IMPLEMENT FETCH DATA AND FILL ARRAYLIST     private void fetchData(DataSnapshot dataSnapshot)     {         spacecrafts.clear();          for (DataSnapshot ds : dataSnapshot.getChildren())         {             Spacecraft spacecraft=ds.getValue(Spacecraft.form);             spacecrafts.add(spacecraft);         }     }      //READ BY HOOKING ONTO DATABASE OPERATION CALLBACKS     public ArrayList<Spacecraft> call up()     {         db.addChildEventListener(new ChildEventListener() {             @Override             public void onChildAdded(DataSnapshot dataSnapshot, String s) {                 fetchData(dataSnapshot);             }              @Override             public void onChildChanged(DataSnapshot dataSnapshot, String s) {                 fetchData(dataSnapshot);              }              @Override             public void onChildRemoved(DataSnapshot dataSnapshot) {              }              @Override             public void onChildMoved(DataSnapshot dataSnapshot, String due south) {              }              @Override             public void onCancelled(DatabaseError databaseError) {              }         });          render spacecrafts;     }  }                  
(c). Our ViewHolder class
  • Holds the views for us to recycle.
  • Subclasses RecyclerView.ViewHolder
          package com.tutorials.hp.firebaserecyclermulti_items.m_UI;  import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.tutorials.hp.firebaserecyclermulti_items.R;  /*  * 1. HOLD VIEWS  */ public class MyViewHolder extends RecyclerView.ViewHolder {      TextView nameTxt,propTxt,descTxt;      public MyViewHolder(View itemView) {         super(itemView);          nameTxt=(TextView) itemView.findViewById(R.id.nameTxt);         propTxt=(TextView) itemView.findViewById(R.id.propellantTxt);         descTxt=(TextView) itemView.findViewById(R.id.descTxt);     } }                  

9. Our MyAdapter class

  • Responsible for Layout Inflation.
  • Also for data binding to views.
  • This class subclasses RecyclerView.Adapter
          package com.tutorials.hp.firebaserecyclermulti_items.m_UI;  import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;  import com.tutorials.hp.firebaserecyclermulti_items.R; import com.tutorials.hp.firebaserecyclermulti_items.m_Model.Spacecraft;  import java.util.ArrayList;  /  * one. LAYOUT Inflation  * 2. RECEIVE SPACECRAFTS  * three. PERFORM Bounden  */ public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {     Context c;     ArrayList<Spacecraft> spacecrafts;      public MyAdapter(Context c, ArrayList<Spacecraft> spacecrafts) {         this.c = c;         this.spacecrafts = spacecrafts;     }      @Override     public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {         View v=LayoutInflater.from(c).inflate(R.layout.model,parent,false);         return new MyViewHolder(v);     }      @Override     public void onBindViewHolder(MyViewHolder holder, int position) {         holder.nameTxt.setText(spacecrafts.become(position).getName());         holder.propTxt.setText(spacecrafts.get(position).getPropellant());         holder.descTxt.setText(spacecrafts.become(position).getDescription());      }      @Override     public int getItemCount() {         return spacecrafts.size();     } }                  
(d). Our MainActivity
  • Launcher activeness.
  • Reference RecyclerView and set its LayoutManager
  • Set its adapter.
  • Shows Input Dialog on FAB push button click.
  • Sets up our Firebase's by initializing the DatabaseReference.
          package com.tutorials.hp.firebaserecyclermulti_items;  import android.app.Dialog; import android.os.Bundle; import android.back up.design.widget.FloatingActionButton; import android.back up.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.back up.v7.widget.RecyclerView; import android.back up.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;  import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.tutorials.hp.firebaserecyclermulti_items.m_FireBase.FirebaseHelper; import com.tutorials.hp.firebaserecyclermulti_items.m_Model.Spacecraft; import com.tutorials.hp.firebaserecyclermulti_items.m_UI.MyAdapter; /* one.INITIALIZE FIREBASE DB ii.INITIALIZE UI 3.Data*/ public class MainActivity extends AppCompatActivity {      DatabaseReference db;     FirebaseHelper helper;     MyAdapter adapter;     RecyclerView rv;     EditText nameEditTxt,propTxt,descTxt;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);         setSupportActionBar(toolbar);          //INITIALIZE RV         rv= (RecyclerView) findViewById(R.id.rv);         rv.setLayoutManager(new LinearLayoutManager(this));          //INITIALIZE FB         db= FirebaseDatabase.getInstance().getReference();          helper=new FirebaseHelper(db);          //ADAPTER         adapter=new MyAdapter(this,helper.recall());         rv.setAdapter(adapter);          FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);         fab.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 displayInputDialog();             }         });     }      //DISPLAY INPUT DIALOG     private void displayInputDialog()     {         //CREATE DIALOG         Dialog d=new Dialog(this);         d.setTitle("Save To Firebase");         d.setContentView(R.layout.input_dialog);          nameEditTxt= (EditText) d.findViewById(R.id.nameEditText);         propTxt= (EditText) d.findViewById(R.id.propellantEditText);         descTxt= (EditText) d.findViewById(R.id.descEditText);         Push button saveBtn= (Button) d.findViewById(R.id.saveBtn);          //Salvage         saveBtn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                  //Become DATA                 Cord name=nameEditTxt.getText().toString();                 String propellant=propTxt.getText().toString();                 String desc=descTxt.getText().toString();                  //SET Information                 Spacecraft s=new Spacecraft();                 due south.setName(name);                 s.setPropellant(propellant);                 s.setDescription(desc);                  //SAVE                 if(name != null && name.length()>0)                 {                     if(helper.salvage(south))                     {                         nameEditTxt.setText("");                         propTxt.setText("");                         descTxt.setText("");                          adapter=new MyAdapter(MainActivity.this,helper.retrieve());                         rv.setAdapter(adapter);                     }                 }else                 {                     Toast.makeText(MainActivity.this, "Name Must Not Be Empty", Toast.LENGTH_SHORT).bear witness();                 }              }         });          d.show();     } }                  

3. Our Layouts

(a). InputDialog.xml
  • defines our input dialogs layout
          <?xml version="1.0" encoding="utf-viii"?> <LinearLayout     android_orientation="vertical" android_layout_width="match_parent"     android_layout_height="match_parent">      <LinearLayout         android_layout_width="fill_parent"         android_layout_height="match_parent"         android_layout_marginTop="?attr/actionBarSize"         android_orientation="vertical"         android_paddingLeft="15dp"         android_paddingRight="15dp"         android_paddingTop="50dp">          <android.support.design.widget.TextInputLayout             android_id="@+id/nameLayout"             android_layout_width="match_parent"             android_layout_height="wrap_content">              <EditText                 android_id="@+id/nameEditText"                 android_layout_width="match_parent"                 android_layout_height="wrap_content"                 android_singleLine="true"                 android_hint= "Name" />         </android.support.pattern.widget.TextInputLayout>          <android.back up.design.widget.TextInputLayout             android_id="@+id/propLayout"             android_layout_width="match_parent"             android_layout_height="wrap_content">              <EditText                 android_id="@+id/propellantEditText"                 android_layout_width="match_parent"                 android_layout_height="wrap_content"                 android_singleLine="truthful"                 android_hint= "Propellant" />          <android.support.pattern.widget.TextInputLayout             android_id="@+id/descLayout"             android_layout_width="match_parent"             android_layout_height="wrap_content">              <EditText                 android_id="@+id/descEditText"                 android_layout_width="match_parent"                 android_layout_height="wrap_content"                 android_singleLine="truthful"                 android_hint= "Description" />         </android.support.design.widget.TextInputLayout>          </android.back up.design.widget.TextInputLayout>          <Button android_id="@+id/saveBtn"             android_layout_width="fill_parent"             android_layout_height="wrap_content"             android_text="Save"             android_clickable="true"             android_background="@color/colorAccent"             android_layout_marginTop="40dp"             android_textColor="@android:color/white"/>      </LinearLayout>  </LinearLayout>        
(b). Model.xml
  • How each view item shall appear.
          <?xml version="1.0" encoding="utf-eight"?> <android.back up.v7.widget.CardView     android_orientation="horizontal" android_layout_width="match_parent"      android_layout_margin="10dp"     card_view_cardCornerRadius="5dp"     card_view_cardElevation="5dp"     android_layout_height="200dp">          <LinearLayout             android_orientation="vertical"             android_layout_width="match_parent"             android_layout_height="match_parent">              <TextView                 android_layout_width="match_parent"                 android_layout_height="wrap_content"                 android_textAppearance="?android:attr/textAppearanceLarge"                 android_text="Proper name"                 android_id="@+id/nameTxt"                 android_padding="10dp"                 android_textColor="@color/colorAccent"                 android_textStyle="bold"                 android_layout_alignParentLeft="true"                 />              <TextView                 android_layout_width="wrap_content"                 android_layout_height="wrap_content"                 android_textAppearance="?android:attr/textAppearanceLarge"                 android_text="Description....................."                 android_lines="3"                 android_id="@+id/descTxt"                 android_padding="10dp"                 android_layout_alignParentLeft="true"                 />              <TextView                 android_layout_width="wrap_content"                 android_layout_height="wrap_content"                 android_textAppearance="?android:attr/textAppearanceMedium"                 android_text="Propellant"                 android_textStyle="italic"                 android_id="@+id/propellantTxt" />      </LinearLayout>  </android.back up.v7.widget.CardView>        

iv. Download

Resource Link
GitHub Browse Scan
GitHub Download Link Download

3. Android Firebase – RecyclerView Chief Detail [Open up Action]

Hello,welcome to our Android Firebase RecyclerView Chief detail tutorial.

This is an android firebase recyclerview tutorial. How to save information to firebase,retrieve and then show that data in a custom gridview.

  • Save data from edittext to google firebase database.
  • Retrieve the data by attaching events to a DatabaseReference example.
  • Demark the data to a csutom gridview using a BaseAdapter subclass.
  • Handle the GridView'due south itemClicks.
  • Open new Activity when a grid item is clicked.
  • Laissez passer information to that new activeness

What Is Firebase Realtime Database?

Firebase Realtime database is a database backend every bit a service Cloud hosted solution that gives us the platform to build rich apps.Normally we are used to making HTTP requests to read or write data against our servers.But not in Firebase.It uses synchronization engineering science that allows it to be realtime,simply nevertheless performant.

Main Feautures?

  • Its realtime .
  • Platfrom Contained.
  • Piece of cake Access Control.
  • It's a NoSQL solution and is heavily optimized for performance.
  • Has Offline capability .
  • Its User Friendly.

Video Tutorial  For more Explanations please bank check our video tutorial below.

Setup

(a) .Create Basic Activeness Project
  1. First create a new project in android studio. Get to File –> New Project.
(b). Create Firebase and Download Configuration File

Caput over to Firebase Console, create a Firebase App, Register your app id and download the google-services.json file. Add information technology to your app folder.

(c). Specify Maven repository URL

Caput over to project level(project binder) build.gradle and

  1. Add together Google services classpath as below
  2. Add together maven repository url
          // Top-level build file where you tin add configuration options common to all sub-projects/modules.  buildscript {     repositories {         jcenter()     }     dependencies {         classpath 'com.android.tools.build:gradle:2.3.iii'         classpath 'com.google.gms:google-services:3.i.0'          // NOTE: Exercise non place your application dependencies here; they vest         // in the private module build.gradle files     } }  allprojects {     repositories {         jcenter()         maven {             url "https://maven.google.com" // Google'southward Maven repository         }     } }  chore clean(blazon: Delete) {     delete rootProject.buildDir }        
(d). Add Firebase Dependencies

Add them in y'all app level(app folder) build.gradle, then

          dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])      testCompile 'junit:junit:four.12'     compile 'com.android.back up:appcompat-v7:23.3.0'     compile 'com.android.back up:design:23.3.0'     compile 'com.android.support:cardview-v7:23.3.0'      compile 'com.google.firebase:firebase-cadre:11.eight.0'     compile 'com.google.firebase:firebase-database:11.8.0' } use plugin: 'com.google.gms.google-services'                  

Make sure you lot apply plugin: 'com.google.gms.google-services' as above.

(e). AndroidManifest.xml
  • Remember to add permission for internet in your manifest file.
          <?xml version="ane.0" encoding="utf-8"?> <manifest     package="com.tutorials.hp.firebaserecyclermdetail">      <uses-permission android_name="android.permission.Internet"/>      <application         android_allowBackup="truthful"         android_icon="@mipmap/ic_launcher"         android_label="@string/app_name"         android_supportsRtl="true"         android_theme="@style/AppTheme">         <action             android_name=".MainActivity"             android_label="@cord/app_name"             android_theme="@style/AppTheme.NoActionBar">             <intent-filter>                 <action android_name="android.intent.activity.MAIN" />                  <category android_name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>         <activity             android_name=".DetailActivity"             android_label="Detail View"             android_theme="@fashion/AppTheme.NoActionBar">         </activity>     </application>  </manifest>        

Coffee Classes

(a). Spacecraft.java
  • Is our Information Object class
  • Must Have an empty constructor.
  • Y'all tin can create,pass data to and apply other constructors
          package com.tutorials.hp.firebaserecyclermdetail.m_Model;  /*  * 1. OUR MODEL Form  */ public class Spacecraft {      String proper name,propellant,clarification;      public Spacecraft() {     }      public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }      public Cord getPropellant() {         return propellant;     }      public void setPropellant(String propellant) {         this.propellant = propellant;     }      public String getDescription() {         return description;     }      public void setDescription(String description) {         this.description = description;     } }        
(b). FirebaseHelper.java
  • Basically,our Crud form.
  • Here we perform reads and writes to Firebase database.
  • To persist data nosotros use setValue().
  • Prior to calling setValue() method,we call button() to ensure we append information to database,not replace.
  • We fill an arraylist with spacecraft objects.
          package com.tutorials.hp.firebaserecyclermdetail.m_FireBase;  import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseException; import com.google.firebase.database.DatabaseReference; import com.tutorials.hp.firebaserecyclermdetail.m_Model.Spacecraft;  import java.util.ArrayList;  /*  * i.Relieve Data TO FIREBASE  * 2. RETRIEVE  * 3.Render AN ARRAYLIST  */ public class FirebaseHelper {      DatabaseReference db;     Boolean saved=zero;     ArrayList<Spacecraft> spacecrafts=new ArrayList<>();      public FirebaseHelper(DatabaseReference db) {         this.db = db;     }      //WRITE IF NOT Naught     public Boolean salve(Spacecraft spacecraft)     {         if(spacecraft==nil)         {             saved=faux;         }else         {             try             {                 db.child("Spacecraft").push().setValue(spacecraft);                 saved=true;              }catch (DatabaseException due east)             {                 e.printStackTrace();                 saved=false;             }         }          render saved;     }      //IMPLEMENT FETCH DATA AND Fill up ARRAYLIST     private void fetchData(DataSnapshot dataSnapshot)     {         spacecrafts.articulate();          for (DataSnapshot ds : dataSnapshot.getChildren())         {             Spacecraft spacecraft=ds.getValue(Spacecraft.course);             spacecrafts.add(spacecraft);         }     }      //READ And so RETURN ARRAYLIST     public ArrayList<Spacecraft> retrieve() {         db.addChildEventListener(new ChildEventListener() {             @Override             public void onChildAdded(DataSnapshot dataSnapshot, String s) {                 fetchData(dataSnapshot);             }              @Override             public void onChildChanged(DataSnapshot dataSnapshot, String south) {                 fetchData(dataSnapshot);              }              @Override             public void onChildRemoved(DataSnapshot dataSnapshot) {              }              @Override             public void onChildMoved(DataSnapshot dataSnapshot, Cord s) {              }              @Override             public void onCancelled(DatabaseError databaseError) {              }         });         return spacecrafts;     } }        
(c). MyViewHolder.coffee
  • Is our viewholder class
  • Holds the views to shown in our RecyclerView
          package com.tutorials.hp.firebaserecyclermdetail.m_UI;  import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView;  import com.tutorials.hp.firebaserecyclermdetail.R;  public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{      TextView nameTxt,propTxt,descTxt;     ItemClickListener itemClickListener;      public MyViewHolder(View itemView) {         super(itemView);          nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);         propTxt= (TextView) itemView.findViewById(R.id.propellantTxt);         descTxt= (TextView) itemView.findViewById(R.id.descTxt);          itemView.setOnClickListener(this);     }      public void setItemClickListener(ItemClickListener itemClickListener)     {         this.itemClickListener=itemClickListener;     }      @Override     public void onClick(View view) {         this.itemClickListener.onItemClick(this.getLayoutPosition());     } }        
(d). MyAdapter.java
  • Responsible for Layout Inflation.
  • Also for data bounden to views.
  • And then opens new action and passes data to information technology via android.Content.Intent.
          package com.tutorials.hp.firebaserecyclermdetail.m_UI;  import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;  import com.tutorials.hp.firebaserecyclermdetail.DetailActivity; import com.tutorials.hp.firebaserecyclermdetail.R; import com.tutorials.hp.firebaserecyclermdetail.m_Model.Spacecraft;  import java.util.ArrayList;  public grade MyAdapter extends RecyclerView.Adapter<MyViewHolder> {      Context c;     ArrayList<Spacecraft> spacecrafts;      public MyAdapter(Context c, ArrayList<Spacecraft> spacecrafts) {         this.c = c;         this.spacecrafts = spacecrafts;     }      @Override     public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {         View v=LayoutInflater.from(c).inflate(R.layout.model,parent,faux);         return new MyViewHolder(v);     }      @Override     public void onBindViewHolder(MyViewHolder holder, int position) {         terminal  Spacecraft s=spacecrafts.go(position);          holder.nameTxt.setText(south.getName());         holder.propTxt.setText(s.getPropellant());         holder.descTxt.setText(s.getDescription());          holder.setItemClickListener(new ItemClickListener() {             @Override             public void onItemClick(int pos) {                 //OPEN DETAI Activeness                 openDetailActivity(s.getName(),southward.getDescription(),south.getPropellant());             }         });     }      @Override     public int getItemCount() {         render spacecrafts.size();     }      //OPEN DETAIL ACTIVITY     private void openDetailActivity(String...details)     {         Intent i=new Intent(c,DetailActivity.course);          i.putExtra("NAME_KEY",details[0]);         i.putExtra("DESC_KEY",details[i]);         i.putExtra("PROP_KEY",details[two]);          c.startActivity(i);     } }        
(due east). ItemClickListener.java
  • Defines for us signature for our onItemClick() method.
          package com.tutorials.hp.firebaserecyclermdetail.m_UI;  public interface ItemClickListener {      void onItemClick(int pos); }        

12. MainActivity.coffee

  • Launcher action.
  • Reference RecyclerView, set its adapter.
  • Shows Input Dialog on FAB push button click.
  • Sets up our Firebase's past initializing the DatabaseReference.
          packet com.tutorials.hp.firebaserecyclermdetail;  import android.app.Dialog; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.back up.v7.app.AppCompatActivity; import android.back up.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;  import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.tutorials.hp.firebaserecyclermdetail.m_FireBase.FirebaseHelper; import com.tutorials.hp.firebaserecyclermdetail.m_Model.Spacecraft; import com.tutorials.hp.firebaserecyclermdetail.m_UI.MyAdapter;  /* 1.INITIALIZE FIREBASE DB 2.INITIALIZE UI 3.Information INPUT  */ public grade MainActivity extends AppCompatActivity {     DatabaseReference db;     FirebaseHelper helper;     MyAdapter adapter;     RecyclerView rv;     EditText nameEditTxt,propTxt,descTxt;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);         setSupportActionBar(toolbar);          //SETUP RECYCLER         rv = (RecyclerView) findViewById(R.id.rv);         rv.setLayoutManager(new LinearLayoutManager(this));          //INITIALIZE FIREBASE DB         db= FirebaseDatabase.getInstance().getReference();         helper=new FirebaseHelper(db);          //ADAPTER         adapter=new MyAdapter(this,helper.retrieve());         rv.setAdapter(adapter);          FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);         fab.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 displayInputDialog();             }         });     }      //Display INPUT DIALOG     private void displayInputDialog()     {         Dialog d=new Dialog(this);         d.setTitle("Save To Firebase");         d.setContentView(R.layout.input_dialog);          nameEditTxt= (EditText) d.findViewById(R.id.nameEditText);         propTxt= (EditText) d.findViewById(R.id.propellantEditText);         descTxt= (EditText) d.findViewById(R.id.descEditText);         Push saveBtn= (Push button) d.findViewById(R.id.saveBtn);          //Salvage         saveBtn.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                  //Get DATA                 String name=nameEditTxt.getText().toString();                 String propellant=propTxt.getText().toString();                 String desc=descTxt.getText().toString();                  //SET DATA                 Spacecraft due south=new Spacecraft();                 s.setName(name);                 due south.setPropellant(propellant);                 s.setDescription(desc);                  //Uncomplicated VALIDATION                 if(name != null && name.length()>0)                 {                     //Then SAVE                     if(helper.relieve(s))                     {                         //IF SAVED CLEAR EDITXT                         nameEditTxt.setText("");                         propTxt.setText("");                         descTxt.setText("");                          adapter=new MyAdapter(MainActivity.this,helper.retrieve());                         rv.setAdapter(adapter);                      }                 }else                 {                     Toast.makeText(MainActivity.this, "Name Must Non Be Empty", Toast.LENGTH_SHORT).testify();                 }              }         });          d.show();     }  }        
(f). DetailActivity.java
  • Yep,the particular activity here.To show our details.
  • Receives data from MainActivity via Intent.
  • Shows the data in TextViews.
          bundle com.tutorials.hp.firebaserecyclermdetail;  import android.content.Intent; import android.os.Parcel; import android.support.blueprint.widget.FloatingActionButton; import android.support.blueprint.widget.Snackbar; import android.back up.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.TextView;  public class DetailActivity extends AppCompatActivity {      TextView nameTxt,descTxt, propTxt;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_detail);         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);         setSupportActionBar(toolbar);         FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);          nameTxt = (TextView) findViewById(R.id.nameDetailTxt);         descTxt= (TextView) findViewById(R.id.descDetailTxt);         propTxt = (TextView) findViewById(R.id.propellantDetailTxt);          //GET INTENT         Intent i=this.getIntent();          //RECEIVE DATA         Cord name=i.getExtras().getString("NAME_KEY");         String desc=i.getExtras().getString("DESC_KEY");         String propellant=i.getExtras().getString("PROP_KEY");          //BIND Data         nameTxt.setText(proper noun);         descTxt.setText(desc);         propTxt.setText(propellant);          fab.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 Snackbar.make(view, "Replace with your own activity", Snackbar.LENGTH_LONG)                         .setAction("Activity", null).show();             }         });     }  }        

Layouts

(a). ActivityMain.xml
  • Contains our ContentMain.xml
  • Defines our Floating ActionButton.
          <?xml version="i.0" encoding="utf-8"?> <android.support.blueprint.widget.CoordinatorLayout      android_layout_width="match_parent"     android_layout_height="match_parent"     android_fitsSystemWindows="true"     tools_context="com.tutorials.hp.firebaserecyclermdetail.MainActivity">      <android.support.design.widget.AppBarLayout         android_layout_width="match_parent"         android_layout_height="wrap_content"         android_theme="@fashion/AppTheme.AppBarOverlay">          <android.back up.v7.widget.Toolbar             android_id="@+id/toolbar"             android_layout_width="match_parent"             android_layout_height="?attr/actionBarSize"             android_background="?attr/colorPrimary"             app_popupTheme="@style/AppTheme.PopupOverlay" />      </android.support.blueprint.widget.AppBarLayout>      <include layout="@layout/content_main" />      <android.support.design.widget.FloatingActionButton         android_id="@+id/fab"         android_layout_width="wrap_content"         android_layout_height="wrap_content"         android_layout_gravity="bottom|cease"         android_layout_margin="@dimen/fab_margin"         android_src="@android:drawable/ic_dialog_email" />  </android.support.design.widget.CoordinatorLayout>                  
(b). ContentMain.xml
  • Our Master View
          <?xml version="1.0" encoding="utf-viii"?> <RelativeLayout      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"     app_layout_behavior="@string/appbar_scrolling_view_behavior"     tools_context="com.tutorials.hp.firebaserecyclermdetail.MainActivity"     tools_showIn="@layout/activity_main">      <android.support.v7.widget.RecyclerView         android_id="@+id/rv"         android_layout_width="match_parent"         android_layout_height="wrap_content"         /> </RelativeLayout>        
(c). inputdialog.xml
  • defines our input dialogs layout
          <?xml version="1.0" encoding="utf-eight"?> <LinearLayout     android_orientation="vertical" android_layout_width="match_parent"     android_layout_height="match_parent">      <LinearLayout         android_layout_width="fill_parent"         android_layout_height="match_parent"         android_layout_marginTop="?attr/actionBarSize"         android_orientation="vertical"         android_paddingLeft="15dp"         android_paddingRight="15dp"         android_paddingTop="50dp">          <android.support.design.widget.TextInputLayout             android_id="@+id/nameLayout"             android_layout_width="match_parent"             android_layout_height="wrap_content">              <EditText                 android_id="@+id/nameEditText"                 android_layout_width="match_parent"                 android_layout_height="wrap_content"                 android_singleLine="true"                 android_hint= "Name" />         </android.support.design.widget.TextInputLayout>          <android.support.design.widget.TextInputLayout             android_id="@+id/propLayout"             android_layout_width="match_parent"             android_layout_height="wrap_content">              <EditText                 android_id="@+id/propellantEditText"                 android_layout_width="match_parent"                 android_layout_height="wrap_content"                 android_singleLine="true"                 android_hint= "Propellant" />          <android.support.design.widget.TextInputLayout             android_id="@+id/descLayout"             android_layout_width="match_parent"             android_layout_height="wrap_content">              <EditText                 android_id="@+id/descEditText"                 android_layout_width="match_parent"                 android_layout_height="wrap_content"                 android_singleLine="true"                 android_hint= "Description" />         </android.support.design.widget.TextInputLayout>          </android.support.pattern.widget.TextInputLayout>          <Push button android_id="@+id/saveBtn"             android_layout_width="fill_parent"             android_layout_height="wrap_content"             android_text="Salve"             android_clickable="true"             android_background="@color/colorAccent"             android_layout_marginTop="40dp"             android_textColor="@android:color/white"/>      </LinearLayout>  </LinearLayout>        
(d). Model.xml
  • defines our custom CardViews.
          <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView     android_orientation="horizontal" android_layout_width="match_parent"      android_layout_margin="10dp"     card_view_cardCornerRadius="5dp"     card_view_cardElevation="5dp"     android_layout_height="200dp">          <LinearLayout             android_orientation="vertical"             android_layout_width="match_parent"             android_layout_height="match_parent">              <TextView                 android_layout_width="match_parent"                 android_layout_height="wrap_content"                 android_textAppearance="?android:attr/textAppearanceLarge"                 android_text="Name"                 android_id="@+id/nameTxt"                 android_padding="10dp"                 android_textColor="@color/colorAccent"                 android_textStyle="assuming"                 android_layout_alignParentLeft="truthful"                 />              <TextView                 android_layout_width="wrap_content"                 android_layout_height="wrap_content"                 android_textAppearance="?android:attr/textAppearanceLarge"                 android_text="Description....................."                 android_lines="3"                 android_id="@+id/descTxt"                 android_padding="10dp"                 android_layout_alignParentLeft="truthful"                 />              <TextView                 android_layout_width="wrap_content"                 android_layout_height="wrap_content"                 android_textAppearance="?android:attr/textAppearanceMedium"                 android_text="Propellant"                 android_textStyle="italic"                 android_id="@+id/propellantTxt" />      </LinearLayout>  </android.back up.v7.widget.CardView>        
(f). activity_detail.xml
  • Contains our ContentDetail.xml
          <?xml version="ane.0" encoding="utf-8"?> <android.back up.design.widget.CoordinatorLayout      android_layout_width="match_parent"     android_layout_height="match_parent"     android_fitsSystemWindows="true"     tools_context="com.tutorials.hp.firebaserecyclermdetail.DetailActivity">      <android.support.blueprint.widget.AppBarLayout         android_layout_width="match_parent"         android_layout_height="wrap_content"         android_theme="@style/AppTheme.AppBarOverlay">          <android.support.v7.widget.Toolbar             android_id="@+id/toolbar"             android_layout_width="match_parent"             android_layout_height="?attr/actionBarSize"             android_background="?attr/colorPrimary"             app_popupTheme="@fashion/AppTheme.PopupOverlay" />      </android.support.blueprint.widget.AppBarLayout>      <include layout="@layout/content_detail" />      <android.back up.blueprint.widget.FloatingActionButton         android_id="@+id/fab"         android_layout_width="wrap_content"         android_layout_height="wrap_content"         android_layout_gravity="bottom|stop"         android_layout_margin="@dimen/fab_margin"         android_src="@android:drawable/ic_dialog_email" />  </android.support.design.widget.CoordinatorLayout>                  
(g). content_detail.xml
  • Our Detail View.
          <?xml version="1.0" encoding="utf-8"?> <RelativeLayout      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"     app_layout_behavior="@string/appbar_scrolling_view_behavior"     tools_context="com.tutorials.hp.firebaserecyclermdetail.DetailActivity"     tools_showIn="@layout/activity_detail">      <android.support.v7.widget.CardView         android_orientation="horizontal" android_layout_width="match_parent"          android_layout_margin="5dp"         card_view_cardCornerRadius="10dp"         card_view_cardElevation="5dp"          android_layout_height="match_parent">          <LinearLayout             android_orientation="vertical"             android_layout_width="match_parent"             android_layout_height="match_parent"             android_weightSum="1">              <LinearLayout                 android_orientation="horizontal"                 android_layout_width="match_parent"                 android_layout_height="wrap_content">                  <ImageView                     android_id="@+id/articleDetailImg"                     android_layout_width="320dp"                     android_layout_height="wrap_content"                     android_paddingLeft="10dp"                     android_layout_alignParentTop="true"                     android_scaleType="centerCrop"                     android_src="@drawable/spitzer" />                  <LinearLayout                     android_orientation="vertical"                     android_layout_width="match_parent"                     android_layout_height="wrap_content">                      <TextView                         android_id="@+id/nameDetailTxt"                         android_layout_width="wrap_content"                         android_layout_height="wrap_content"                         android_textAppearance="?android:attr/textAppearanceLarge"                         android_padding="5dp"                         android_minLines="i"                         android_textStyle="assuming"                         android_textColor="@color/colorAccent"                         android_text="Title" />                  </LinearLayout>             </LinearLayout>              <LinearLayout                 android_layout_width="fill_parent"                 android_layout_height="match_parent"                 android_layout_marginTop="?attr/actionBarSize"                 android_orientation="vertical"                 android_paddingLeft="5dp"                 android_paddingRight="5dp"                 android_paddingTop="5dp">                  <TextView                     android_id="@+id/propellantDetailTxt"                     android_layout_width="wrap_content"                     android_layout_height="wrap_content"                     android_textAppearance="?android:attr/textAppearanceLarge"                     android_padding="5dp"                     android_minLines="1"                     android_text="Date" />                 <TextView                     android_id="@+id/descDetailTxt"                     android_layout_width="wrap_content"                     android_layout_height="wrap_content"                     android_textAppearance="?android:attr/textAppearanceLarge"                     android_padding="5dp"                     android_textColor="#0f0f0f"                     android_minLines="4"                     android_text="Space craft details...." />                  <TextView                     android_id="@+id/linkDetailTxt"                     android_layout_width="wrap_content"                     android_layout_height="wrap_content"                     android_textAppearance="?android:attr/textAppearanceMedium"                     android_padding="5dp"                     android_textColor="@color/colorPrimaryDark"                     android_textStyle="italic"                     android_text="Link" />              </LinearLayout>         </LinearLayout>     </android.support.v7.widget.CardView>  </RelativeLayout>                  

four. Download

Resource Link
GitHub Browse Browse
GitHub Download Link Download
Video Video tutorial

How To Run

  1. Download the project.
  2. Y'all'll get a zipped file,extract information technology.
  3. Open the Android Studio.
  4. Now close, already open projection.
  5. From the Menu bar click on File >New> Import Project.
  6. Now Cull a Destination Folder, from where you want to import projection.
  7. Choose an Android Project.
  8. At present Click on "OK".
  9. Done, your done importing the project,now edit it.
  10. You'll demand to head over to Firebase Console, create app, then download configuration file and add together to your projection in the app folder.

Ezoic

heinemanthros1965.blogspot.com

Source: https://camposha.info/android-examples/android-firebase-recyclerview/

0 Response to "Upload and Retrieve Data in Firebase in Cardview"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel