- How to Create Dynamic ListView in Android using Firebase Firestore?
- What we are going to build in this project?
- Step by Step Implementation
- Android Firebase Realtime Database ListView CRUD simple examples
- 1. Android Firebase – ListView – Save,Retrieve,Show
- The Plan
- 1. Setup
- 5. Create User Interface
- Our Java Classes
- (b). Our FirebaseHelper class
- Download
- 2. Android Firebase – ListView Multiple Fields – Save,Retrieve then Show
- 2. XML Layouts
- Java Classes
- 10. Reminders
- 4. Download
- 3. Android Firebase – ListView Master Detail – Save,Retrieve,Show [Open Activity]
- Project Summary
- Setting Up
- Our Classes.
- (a). Spacecraft.java
- 3. Our Layouts
- (d). activity_detail.xml
- 4. Download
- How To Run
- Example 4: Android Firebase ListView – Write, Read, Scroll to Last Added Item
- We are Building a Vibrant YouTube Community
- Firebase Pre-requisites
- 1. Create Android Studio Application
- 2. Create Firebase App in Firebase Console
- 3. Register App
- 4. Download google-services.json
- 5. Copy google-services.json to Your App Folder
- Build.Gradle(Project Level)
- (a). Add Google Services Class Path
- (b). Register Google Maven’s Repository
- Build.Gradle(App Level)
- (a). Add Firebase Dependencies
- (b).Apply Google Services Plugin
- RESOURCES
- colors.xml
- styles.xml
- styles.xml(v21)
- AndroidManifest.xml
- activity_main.xml
- model.xml
- input_dialog.xml
- Java Code
- Teacher.java
- MainActivity.java
- 1. Create Class,Package and Add Imports
- 3. Create a Firebase Helper class
- Construct our FirebaseHelper
- How to Save Data to Firebase Database
- How to Read/Retrieve Data From Firebase
- How to Smooth Scroll ListView to Recently Added Firebase Item
- How to Use BaseAdapter with Firebase Data
- How to Create an Input Form in a Custom Dialog
- Full Code
- Result
- Issues to Keep in Mind
- Oclemy
How to Create Dynamic ListView in Android using Firebase Firestore?
ListView is one of the most used UI components in Android which you can find across various apps. So we have seen listview in many different apps. In the previous article, we have seen implementing ListView in Android using Firebase Realtime Database. Now in this article, we will take a look at the implementation of ListView using Firebase Firestore in Android. Now, let’s move towards the implementation of this project.
What we are going to build in this project?
We will be building a simple ListView application in which we will be displaying a list of courses along with images in our ListView. We will fetch all the data inside our ListView from Firebase Firestore. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a new Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Connect your app to Firebase
After creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.
Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen.
After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section.
After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App.
Step 3: Working with the AndroidManifest.xml file
For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it.
Step 4: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
Step 5: Now we will create a new Java class for storing our data
For reading data from the Firebase Firestore database, we have to create an Object class and we will read data inside this class. For creating an object class, navigate to the app > java > your app’s package name > Right-click on it and click on New > Java Class > Give a name to your class. Here we have given the name as DataModal and add the below code to it.
Step 6: Create a layout file for our item of ListView
Navigate to the app > res > layout > Right-click on it and click on New > Layout Resource File and give a name to that file. After creating that file add the below code to it. Here we have given the name as image_lv_item and add the below code to it.
Step 7: Now create an Adapter class for our ListView
For creating a new Adapter class navigate to the app > java > your app’s package name > Right-click on it and Click on New > Java class and name your java class as CoursesLVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail.
Step 8: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
After adding the above code add the data to Firebase Firestore in Android.
Step 9: Adding the data to Firebase Firestore in Android
Search for Firebase in your browser and go to that website and you will get to see the below screen.
After clicking on Go to Console option. Click on your project which is shown below.
After clicking on your project you will get to see the below screen. After clicking on this project you will get to see the below screen.
After clicking on the Create Database option you will get to see the below screen.
Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen.
Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we have to add the data inside our Firebase Console. For adding data to our Firebase Console.
You have to click on Start Collection Option and give the collection name as Data. After creating a collection you have to click on Autoid option for creating the first document. Then create two fields, one filed for “name” and one filed for “imgUrl” and enter the corresponding values for them. Note that specify the image URL link in the value for the imgUrl filed. And click on the Save button. Your first image to the Data has been added.
Similarly, add more images by clicking on the “Add document” button.
After adding these images run your app and you will get to see the output on the below screen.
Источник
Android Firebase Realtime Database ListView CRUD simple examples
Android Firebase Realtime Database – 3 ListView Examples
This is an android Firebase Realtime Database with ListView examples. We see how to add and retrieve data and show in ListViews.
1. Android Firebase – ListView – Save,Retrieve,Show
So lets cover android firebase listview example.How to save from edittext,retrieve that particular data and of course show in a simple listview.
ListView is one of the most popular adapterviews while Firebase is probably the most popular database backend service currently in the market.
These two are easy to use and provides us with powerful opportunities to create amazing apps.
The Plan
This android firebase listview tutorial.This is what we do :
- Save from edittext to google firebase database using methods setValue() and push() ;
- Fetch that particular data by attaching a childEventListener to a databaseReference instance.
- Read the children of a dataSnapshot.
- Fill Simple ArrayList
- Bind the arraylist to ListView
1. Setup
(a). Create Basic Activity Project
- First 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). Add Google services classpath and maven url
Add classpath ‘com.google.gms:google-services:3.1.0’ . This you do in the project level build.gradle. You may use later versions.
Also add the google maven url in you respositories. Firebase will be fetched from that url.
(c). Add Firebase Dependencies
Add FirebaseDatabase dependencies in your app level build.gradle. You may use later versions than me. Then sync the project to download them and add them as part of your project.
Make sure you apply plugin: ‘com.google.gms.google-services’ as above.
(d). AndroidManifest.xml
- Add this to your androidmainfest.xml file. This because to access Firebase we need internet connection hence we have to specify a permission. Add it under the .. tag.
5. Create User Interface
User interfaces are typically created in android using XML layouts as opposed by direct java coding.
(a). activity_main.xml
- This layout gets inflated to MainActivity user interface.
- It includes the content_main.xml.
(b). content_main.xml
This layout will get interpolated into our activity_main.xml .
Here are the roles of this layout:
No. | Responsibility |
---|---|
1. | Define a ListView identified by a unique id. That ListView is our adapterview and will render our realtime data from Firebase. |
(c). input_dialog.xml
This is our input form layout.
Here are it’s roles:
No. | Responsibility |
---|---|
1. | Define an EditText for writing data to firebase. Wrap that edittext in a TextInputLayout to give it a material design feel. |
2. | Define a Button to be used as our action button to for saving data to firebase. |
3. | Align all these widgets in a vertical manner with the help of a LinearLayout. |
Our Java Classes
(a). Our Model Class : Spacecarft.java
- Data object
- Represents a single spacecraft and its properties.
It has the following responsibilities:
No. | Responsibility |
---|---|
1. | Define one private field which will be the sole property of our spacecraft. That is : name property. |
2. | Define one empty constructor which is require by Firebase. |
3. | Expose our instance field for modification or data retrieval via setter and getter methods respectively. |
(b). Our FirebaseHelper class
- Perform basic Write to Firebase database
- Read from Firebase database.
- Fill simple arraylist
Here are the major responsibilities of this class:
No. | Responsibility |
---|---|
1. | Maintain three instance fields: a DatabaseReference , a Boolean and an ArrayList . |
2. | Obtain a DatabaseReference via the parameter from outside and assign it to the one we maintain locally. |
3. | Define a public method save() that receives a Spacecraft object, then attempt to save it to Firebase and return either true or false based on the success. To save data we use db.child(«Spacecraft»).push().setValue(spacecraft) . |
4. | Define a private helper method called fetchData() that receives a com.google.firebase.database.DataSnapshot object. Then loop through the children of this DataSnapshot getting the value of each DataSnapshot child via datasnapshotChild.getValue(Spacecraft.class) . Add these values into our private ArrayList. |
5. | Define a method retrieve() . Add child event listeners to our private DatabaseReference we had maintained. When any DataSnapshot child changes or gets added, call our fetchData() passing in that DataSnapshot as a parameter. This is how fetch data. Then return the filled arraylist. |
(c). Our MainActivity class
- Launcher activity
- Where we bind to listview to our data using arrayadapter
- Initialize DatabaseReference
- Show input dialog
It derives from android.support.v7.app.AppCompatActivity .
Here are it’s major responsibilities:
No. | Responsibility |
---|---|
1. | Allow itself to become an android activity component by deriving from android.support.v7.app.AppCompatActivity . |
2. | Listen to activity creation callback by overrding the onCreate() method. |
3. | Invoke the onCreate() method of the parent Activity class and tell it of a Bundle we’ve received. |
4. | Inflate the activity_main.xml into a View object and set it as the content view of this activity. |
5. | Search for a toolbar by it’s id and set it as our actionbar. |
6. | Host an input dialog that will be used to save data into Firebase Realtime database. |
7. | Search for the EditText and Button from our layout and return them as view objects.These widgets will help users perform this data insertion. This by saving data from these EditTexts when the save button is clicked. |
8. | Find ListView by its id from our layouts. |
9. | Obtain a com.google.firebase.database.FirebaseDatabase instance then obtain a DatabaseReference from that instance then assign it to our local DatabaseReference private field. |
10. | Instantiate our CustomAdapter, pass it our data then set the adapter to our ListView. |
11. | Reference our FloatingActionButton from our activity_main.xml , then listen to its onClick events, then when it’s clicked display our input Dialog. |
Download
Resource | Link |
---|---|
GitHub Browse | Browse |
GitHub Download Link | Download |
2. Android Firebase – ListView Multiple Fields – Save,Retrieve then Show
This is an android firebase ListView tutorial. We see how to save data to firebase,retrieve then show that data in a custom ListView.
- Save data from edittext to google firebase database.
- Retrieve the data by attaching events to a DatabaseReference instance.
- Bind the data to a custom gridview using Subclass.
(a). Create Basic Activity Project
- First create a new project in android studio. Go to File –> New Project.
(b) Create Firebase App
Go to Firbese Console and create a Firebase App. Then register add your android application ID into that app and download the google-services.json file.
There is a wizard that will guide you through this process inside the Firebase Console dashboard.
(c). Add Google services classpath and maven url
Add classpath ‘com.google.gms:google-services:3.1.0’ . This you do in the project level build.gradle . You may use later versions.
Also add the google maven url in you respositories. Firebase will be fetched from that url.
(d). Add Firebase Dependencies
Add FirebaseDatabase dependencies in your app level build.gradle. You may use later versions than me. Then sync the project to download them and add them as part of your project.
Make sure you apply plugin: ‘com.google.gms.google-services’ as above.
(e). AndroidManifest.xml
- Remember to add permission for internet in your manifest file. This is because Firebase is cloud based and we need internet connection permission to access internet in android.
2. XML Layouts
Here are our layouts for this project:
(a). activity_main.xml
- This layout gets inflated to MainActivity user interface.
- It includes the content_main.xml.
(b). ContenMain.xml
This is alayout that will get included as part of our activity_main.xml layout.
Here are the roles of this layout:
No. | Responsibility |
---|---|
1. | Define a ListView identified by a unique id. That ListView is our adapterview and will render our realtime data from Firebase. |
(c). InputDialog.xml
This is our input form layout.
Here are it’s roles:
No. | Responsibility |
---|---|
1. | Define three EditTexts for writing data to firebase. Wrap those edittexts in a TextInputLayout to give them a material design feel. |
2. | Define a Button to be used as our action button to for saving data to firebase. |
3. | Align all these widgets in a vertical manner with the help of a LinearLayout. |
(d). Model.xml
This is our ListView row model layout.
It has the following responsibilities:
No. | Responsibility |
---|---|
1. | Define three TextViews for displaying each spacecraft’s details. |
2. | Align those TextViews vertically using a LinearLayout. |
3. | Define a root CardView to wrap all these under one roof. |
Java Classes
(a). Spacecraft.java
- This is our Data Object class
- Note that it Must Have an empty constructor.
- You can create,pass data to and use other constructors
This is our ListView row model layout.
It has the following responsibilities:
No. | Responsibility |
---|---|
1. | Define three private fields which will act as the properties of this spacecraft. These include: name , propellant and description . |
2. | Define one empty constructor which is requireb by Firebase. |
3. | Expose our instance fields for modifications or data retrieval via setters and getters respectively. |
(b). Our FirebaseHelper Class
- 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 we append data to database,not replace.
- We fill an arraylist with model objects.
Here are the major responsibilities of this class:
No. | Responsibility |
---|---|
1. | Maintain three instance fields: a DatabaseReference , a Boolean and an ArrayList . |
2. | Obtain a DatabaseReference via the parameter from outside and assign it to the one we maintain locally. |
3. | Define a public method save() that receives a Spacecraft object, then attempt to save it to Firebase and return either true or false based on the success. To save data we use db.child(«Spacecraft»).push().setValue(spacecraft) . |
4. | Define a private helper method called fetchData() that receives a com.google.firebase.database.DataSnapshot object. Then loop through the children of this DataSnapshot getting the value of each DataSnapshot child via datasnapshotChild.getValue(Spacecraft.class) . Add these values into our private ArrayList. |
5. | Define a method retrieve() . Add child event listeners to our private DatabaseReference we had maintained. When any DataSnapshot child changes or gets added, call our fetchData() passing in that DataSnapshot as a parameter. This is how fetch data. Then return the filled arraylist. |
(c). : Our CustomAdapter class
Our adaoter class.
- Responsible for Layout Inflation.
- Also for data binding to views.
- Handling ItemClicks as well
- This class subclasses BaseAdapter
Here are it’s roles:
No. | Responsibility |
---|---|
1. | Accept the responsibilities of an adapter by deriving from the android.widget.BaseAdapter . |
2. | Maintain private Context and ArrayList instance fields. |
3. | Receive a Context and an ArrayList from outside and assign them to the ones we maintain locally. |
4. | Return the count of items to be rendered by our adapter. We do this using the getCount() method. |
5. | Return a particular spacecraft from via the getItem() method as long as you pass us it’s position. |
6. | Use individual spacecraft’s positions in the adapter as their unique ids. |
7. | Inflate our model.xml using the LayoutInflater class and return the resultant view object. All these are done inside the getView() method. |
8. | Listen to each inflated view’s row click events thus showing a Toast message. |
(d). Our MainActivity
- Launcher activity.
- Reference ListView and set its adapter.
- Shows Input Dialog on FAB button click.
- Sets up our Firebase’s by initializing the DatabaseReference.
It derives from android.support.v7.app.AppCompatActivity .
Here are it’s major responsibilities:
No. | Responsibility |
---|---|
1. | Allow itself to become an android activity component by deriving from android.support.v7.app.AppCompatActivity . |
2. | Listen to activity creation callback by overrding the onCreate() method. |
3. | Invoke the onCreate() method of the parent Activity class and tell it of a Bundle we’ve received. |
4. | Inflate the activity_main.xml into a View object and set it as the content view of this activity. |
5. | Search for a toolbar by it’s id and set it as our actionbar. |
6. | Host an input dialog that will be used to save data into Firebase Realtime database. |
7. | Search for the various EditTexts and Buttons from our layout and return them as view objects.These widgets will help users perform this data insertion. Then save data from these EditTexts when the save button is clicked. |
8. | Find ListView by its id from our layouts. |
9. | Obtain a com.google.firebase.database.FirebaseDatabase instance then obtain a DatabaseReference from that instance then assign it to our local DatabaseReference private field. |
10. | Instantiate our CustomAdapter, pass it our data then set the adapter to our ListView. |
11. | Reference our FloatingActionButton from our activity_main.xml , then listen to its onClick events, then when it’s clicked display our input Dialog. |
10. Reminders
- Remember to add permission for internet in your manifest file. This is because Firebase is cloud based and we need internet connection permission to access internet in android.
4. Download
Resource | Link |
---|---|
GitHub Browse | Browse |
GitHub Download Link | Download |
3. Android Firebase – ListView Master Detail – Save,Retrieve,Show [Open Activity]
*his is an Android Firebase ListView Master Detail tutorial. We see how to save to Firebase from our android app, retrieve data, and show in a ListView.
The ListView will be rendered in our Master View.
Then when a ListView item is clicked we open a new activity, our detail activity. Our ListView will comprise a List of Spacecraft objects.
So in the detail view we show the details of the clicked Spacecraft.
- Save data from edittext to google firebase database.
- Retrieve the data by attaching events to a DatabaseReference instance.
- Bind the data to a custom ListView using a BaseAdapter subclass.
- Handle the ListView’s itemClicks.
- Open new Activity when a grid item is clicked.
- Pass data to that new activity
Project Summary
Here’s the Project Summary
No. | File | Major Responsibility |
---|---|---|
1. | Spacecraft.java | Represents a single Spacecraft and it’s properties like name,propellant and description. |
2. | FirebaseHelper.java | This class has allows us perform Firebase CRUD operations. |
3. | CustomAdapter.java | Our adapter class |
4. | DetailActivity.java | Our Detail Activity to show a single spacecraft’s details. |
5. | MainActivity.java | Our Master Activity. It shows the list of Spacecrafts |
6. | activity_main.xml | Our Master Activity’s layout. |
7. | content_main.xml | Our Master Activity’s content detail. |
8. | activity_detail.xml | Our Detail Activity’s main layout. |
9. | content_detail.xml | Our Detail Activity’s content layout. |
10. | input_dialog.xml | Our input dialog layout. |
11. | model.xml | Each ListView’s grid model. |
Setting Up
(a). Create Basic Activity Project
- First 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(project folder) build.gradle and
- Add Google services classpath as below
- Add maven repository url
(c). Add Firebase Dependencies
Add them in you app level(app folder) build.gradle, then
Make sure you apply plugin: ‘com.google.gms.google-services’ as above.
(d). AndroidManifest.xml
- Remember to add permission for internet in your manifest file.
Here’s mine in full:
Our Classes.
So now we look at the Java classes. Basically we have 5 classes; one data object, one adapter class, one FirebaseHelper class and two activities.
(a). Spacecraft.java
This is our data object class. It represents a single Spacecraft. It’s our POJO class. Here’s its responsibilities:
No. | Responsibility |
---|---|
1. | Represents a Single Spacecraft |
2. | Set Spacecraft properties: name,propellant and description. |
3. | Get Spacecraft properties: name,propellant and description. |
- Is our Data Object class
- Must Have an empty constructor.
- You can create,pass data to and use other constructors
(b). Our FirebaseHelper Class
- 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 we append data to database,not replace.
- We fill an arraylist with spacecraft objects.
This class allows us perform save and retrieve data to Firebase Realtime database.
No. | Responsibility |
---|---|
1. | Keep hold of three Objects: DatabaseReference,a Boolean saved value, and an ArrayList of Spacecrafts. |
2. | Obtain a DatabaseReference object via the constructor and Assign it to our local db data member. |
3. | Take a Spacecraft object and save it to Firebase this returning a Boolean indicating success or failure. |
4. | Loop through DataSnapshot children nodes obtaining all the Spacecraft objects from Firebase and fill our local arraylist with those objects. |
5. | Listen to Firebase Children mutation events like when a DataSnapshot child has been added, moved, removed, changed or cancelled. This allows us to fetch data in realtime. |
(c). Our CustomAdapter class
- Responsible for Layout Inflation.
- Also for data binding to views.
- Then opens new activity and passes data to it via android.Content.Intent.
This is our adapter class. It derives from BaseAdapter.
No. | Responsibility |
---|---|
1. | This class will maintain a Context object that will be used to during layout inflation. Furthermore we declare an ArrayList of Spacecrafts that will be bound to our listview. |
2. | Receive a Context and ArrayList of Spacecrafts from outside and assign them to our local instance fields. |
3. | Return data list count,Item and Item Identifier. |
4. | Inflate our model.xml layout and return it as a View when the getView() is called. |
5. | Listen to the inflated View click event and open our Master activity. |
6. | Pass the clicked spacecraft’s details to the Detail Activity. |
(d). Our MainActivity
This is our MainActivity. Our project has two activities and this is the main one. It will be the one launched when we launch our application.
It is also our Master View and will contain a list of Spacecraft objects.
- Launcher activity.
- Reference ListView set its adapter.
- Shows Input Dialog on FAB button click.
- Sets up our Firebase’s by initializing the DatabaseReference.
No. | Responsibility |
---|---|
1. | It will maintain a couple of objects as instance fields including: DatabaseReference,FirebaseHelper,CustomAdapter, ListView and three EditTexts. |
2. | Define a method to instantiate our Dialog object, set it’s title, set its ConteView and finally show it.This dialog is our input dialog with edittexts and save/retrieve buttons. |
3. | Search all the input widgets defined in input_dialog.xml and assign them to their respective instance objects.These include EditTexts and Buttons. |
4. | Listen to Save button click events, then obtain edittext values, assign those values to a Spacecraft object and with the help of FirebaseHelper instance send that object to Firebase realtime database. |
5. | Override the onCreate() method,call it’s super equivalence. |
6. | Find Toolbar in our layout and use it as our actionbar. |
7. | Get FirebaseDatabase instance then it’s reference and pass it to our FirebaseHelper constructor. |
8. | Instantiate CustomAdapter , find listview from our layout, then assign the adapter to the listview. |
9. | Listen to FAB button click event and show the input dialog. |
(e). Our DetailActivity
Go ahead create a SecondActivity that will be used as the Detail View.
It will display selected Spacecraft details.
We’ll look at its source later. However note that it will add two XML layouts: activity_detail and content_detail to our layout resources.
- The DetailActivity will show our details.
- Receives data from MainActivity via Intent.
- Shows the data in TextViews.
Here’s it’s responsibilities and how it works:
No. | Responsibility |
---|---|
1. | Maintain three TextView objects as private instance fields that will be used to show Spacecraft details. |
2. | Override the onCreate() method. Call the super class version of onCreate() as well. |
3. | Inflate the activity_detail via the setContentView() to a View object and set it as the detail Activity’s main UI. |
4. | Find the toolbar from activity_detail and set it as the actionbar of our SecondActivity. |
5. | Find TextViews defined in the content_detail.xml and assign them to our local TextView objects. |
6. | Retrieve the Intent assoicated with our DetailActivity via the getIntent() call. |
7. | Obtain name, description and propellant of our Spacecraft via the getExtras() method calls of our Intent.Then set those values to our TextView objects. |
3. Our Layouts
(a). activity_main.xml
- This layout gets inflated to MainActivity user interface.
- It includes the content_main.xml.
- MainActivity is our Master View.
(b). ContentMain.xml
This layout gets included in your activity_main.xml.
We define our ListView here.
- Our Master View
- Holds our ListView
(c). InputDialog.xml
This is layout will get inflated into a Dialog.
The dialog will have a couple of EditTexts and a Button for saving data to Firebase.
Basically this will be our input dialog.
(c).Model.xml
This is the custom row model for our ListView. It basically defines how each ListViewItem will appear.
In our case we have multiple TextViews to display the properties of each Spacecraft.
At the root we have a CardView:
(d). activity_detail.xml
This is the main layout for our SecondActivity.java which is our DetailActivity. This layout is basically similar to activity_main.xml .
(e).ContentDetail.xml
This layout will get included in the activity_detail.xml .
We add a CardView with a couple of TextViews here that will be used to render data from the Master activity.
4. Download
Resource | Link |
---|---|
GitHub Browse | Browse |
GitHub Download Link | Download |
Video Tutorial | Video |
How To Run
- Download the project.
- You’ll get a zipped file,extract it.
- Open the Android Studio.
- Now close, already open project.
- From the Menu bar click on File >New> Import Project.
- Now Choose a Destination Folder, from where you want to import project.
- Choose an Android Project.
- Now Click on “OK“.
- Done, your done importing the project,now edit it.
- You’ll need to head over to Firebase Console, create app, then download configuration file and add to your project in the app folder.You also have to allow writes and reads from the FirebaseDatabase without authentication.
Example 4: Android Firebase ListView – Write, Read, Scroll to Last Added Item
This is an android Firebase ListView Write, Read and Scroll to Last saved or added item position.
We insert or save data to firebase. After saving data, we automatically fetch or read data from the firebase.
Then populate a custom listview with cardviews. The CardViews have several textviews to display our data.
We then smooth scroll automatically to the last item in the listview.
This tutorial was requested by a community member in our Youtube Channel ProgrammingWizards TV.
We are Building a Vibrant YouTube Community
We have a fast rising YouTube Channel of friends. So far we’ve accumulated more than 2.6 million agreggate views and more than 10,000 subscribers. Here’s the Channel: ProgrammingWizards TV.
Please go ahead subscribe(free obviously) as well. If you have a question or a comment you can post there instead of in this site.People are suggesting us tutorials to do there so you can too.
Here’s this tutorial in Video Format.
Firebase Pre-requisites
To work with Firebase from android, you need the following:
- An android device/emulator running Android 4.0(Ice Cream Sandwich) or newer and Google Play Services 15.0.0 or higher.
- Android Studio. Prefer later versions.
1. Create Android Studio Application
Go over to android studio and create a project as usual. You can choose Empty Activity.
2. Create Firebase App in Firebase Console
Switch on your internet and go to Firebase Console in your browser. You’ll need a Gmail account to login.
First you need to create a Firebase App in the online Firebae Console.
Then Click Add Project.
Then Click Add App as below:
Then choose Android as we are creating android app.
.
3. Register App
After creating a Firebase App you need to associate it with your android application. We call this registering your android app.
You need to type the Android application’s package name. You can get this in your app level build.gradle.
Then click next.
4. Download google-services.json
Next we download a google-services.json file which will contain our configurations.
It will be generated automatically. Just click download to download it.
Let’s now move to Android Studio
5. Copy google-services.json to Your App Folder
In your project, there is an app folder. Copy the downloaded google-services.json there.
You can do this in two ways. First navigate over to project files and just copy paste the file as below:
Alternatively, just move over to the folder via File Explorer and paste the file.
.
We now need to add Firebase SDK to our android application.
So let’s proceed to writing simple gradle statements.
Build.Gradle(Project Level)
(a). Add Google Services Class Path
Go to your open project level or root level build.gradle and specify the class path of google-services plugin.
Please don’t forget to register the class path for google-services. Failure to do so will lead to you getting Default FirebaseApp is not initialized illegal state exception at runtime.
(b). Register Google Maven’s Repository
This you do in your project level build.gradle as well under the allProjects repositories:
So our project level build.gradle should like this:
Build.Gradle(App Level)
(a). Add Firebase Dependencies
Go over to app level build.gradle and add Firebase dependencies.
In this case we require two:
- Firebase Core – The core classes for Firebase.
- FirebaseDatabase – To allow us perform CRUD Firebase Operations.
(b).Apply Google Services Plugin
In the same app level build.gradle, apply the google services plugin just below the dependencies:
Please don’t forget to apply this plugin. Failure to do so will lead to you getting Default FirebaseApp is not initialized illegal state exception at runtime.
So it the app level build.gradle should look like this:
RESOURCES
colors.xml
We are creating and using custom material theme or style to use with our application. Go check the demo or video to see it.
So we need some custom material colors.
Copy paste this code into colors.xml located in the res/values folder.
You can of course change the colors.
styles.xml
We come here and create a custom material design theme that we will be using.
Here’s the code. You can just copy paste this.
styles.xml(v21)
Also create a secondary style in the res/values folder. Name it styles-v21 .
This will be used for Android Lollipop.
AndroidManifest.xml
Those styles we created have to be supplied in our application element’s theme attribute in our AndroidManifest.xml for them to be applied.
Also we need to add permission for internet connectivity.
Here’s the full code. If you copy paste this then change the package name to your package name.
activity_main.xml
In android user interfaces can be created either programmatically or via XML layouts.
The latter is the most common as its the most flexible yet the easiest way.
XML stands for eXtensible Markup Language. We can use it not only to create user interfaces, but also to exchange data.
We start by specifying our root element, in this case a RelativeLayout, which normally arranges items relative to each other.
Inside it at the top we have a TextView, which is a view mostly used to render static text. Think of something like a label. In this case we use it to show the header of our application.
Then we also add a ListView element. This ListView wiil display our data vertically, in a one dimensional manner. The ListView has to be assigned a unique id since it will be referenced from the java code.
We will place it below the header TextView by using the android:layout_below .
We will always be showing a fastScroll . Using this users can scroll through the data. It will be always visible, whether our data exceeds the viewport or not. This is optional.
Moreover the ListView will be aligned to the left and start of the parent.
Then to the bottom right of our parent, which in this case is the RelativeLayout , we will display a FloatingActionButton .
When this FAB button is clicked, an input form will be displayed for users to enter data to be sent to Firebase Realtime Database.
We set it’s layout gravity to bottom|end to place it at the bottom of the screen.
model.xml
This is a layout that will define how each row in our listview will appear.
That’s why we call it model . Our ListView is custom and will be rendering CardViews with multiple Texts. The data will be coming from Firebase Realtime database.
So we place a CardView as a root element of our layout. I have set my cardCornerRadius to 5p , my cardElevation to 10dp and the height to 200dp .
I will use a LinearLayout to arrange items in a vertical manner. These items are basically TextViews.
They will display details of each Teacher object, like name , quote and description .
Here’s the full source code:
input_dialog.xml
So I now create another layout file called input_dialog.xml .
This layout will define for us a Form, an input form we will use to save data to Firebase. User will type data and click save and then we send or write that data to Firebase.
Immediately data will be retrieved and our ListView will get populated. All this happens in realtime since we are using the powerful Firebase Realtime database.
In my Form I will TextViews, EditTexts ad a save button.
Let’s now move to our java code.
Java Code
We have multiple classes but only two files:
- Teacher.java – Our model class.
- MainActivity.java – To contain three inner clases.
Doing it this way makes it easy for beginners to copy paste the code and edit it without creating a bunch of java files.
Teacher.java
This is our model class. It represents a single Teacher. It is our data object.
This class is very important in the way we are working with Firebase. This is because we are saving type safe classes to Firebase.
Then Firebase will automatically read this class and create a JSONObject based on our class names and properties.
You must supply an empty constructor for the class.
MainActivity.java
Let’s move line by line for our main activity.
1. Create Class,Package and Add Imports
Android projects are normally written in java and kotlin. In both classes are entities to encapsulate code and classes themselves are hosted in packages.
In both we add import statemments via the import keyword.
A class is then created via the class keyword. And the accessibility modifier can be specified.
Both being Object Oriented Programming languages, they support inheritance.
We are using java in this case. Class inheritance in java is achieved through use of the extends keyword:
That has now turned an ordinary class into a special class, an android component called activity.
3. Create a Firebase Helper class
A class that will be responsible for the following:
- Writing/Saving data to Firebase From EditText.
- Reading/Retrieving data from Firebase.
- Setting Firebase Data to Adapter.
- Binding the Adapter to ListView for viewability of the data.
Creating the class is easy, we do it inside the MainActivity as an inner class:
We will give this FirebaseHelper class some instance fields including:
- DatabaseReference – Our Firebase realtime database reference, pointing us to the database.
- Boolean field saved – To hold the state of our save to firebase attempt.
- ArrayList teachers – To hold all the data we read or fetch from our firebase realtime database.
- ListView mListView – To hold a reference to the ListView which will display our data from the Firebase.
- Context c – This will hold a reference that will be required while instantiating our custom adapter.
Add them inside the FirebaseHelper class:
Construct our FirebaseHelper
We have our constructor, a special method that normally gets called when a class in instantiated.
In our case we will inject several dependencies to our class via the constructor.
These include the:
- Firebase DatabaseReference object.
- Context object.
- ListView object.
We will also invoke a method called retrieve() which will peform our firebase data retrieval.
How to Save Data to Firebase Database
Saving data to Firebase database is very easy. This saving is sometimes called a write operation. Or insert .
We can easily save a custom object like say User or Teacher into firebase database. Then these will be stored in a JSONObject-like nodes.
To save data to Firebase from our app, first let’s create a method called save() that takes in a custom POJO object like Teacher :
In this case the method is returing a Boolean value representing our success state.
Then we first check whether we have valid data. If null is passed to us we just ignore the process and return from execution without saving:
Otherwise we create a try-catch block to catch any runtime exceptions without crashing our app:
In Firebase multiple users can save data at the same time by pushing the data via the push() method.
But first you need the Child node(like a Table) where we push that data. We can get it from our DatabaseReference object
We set the value we want to push or save to Firebase database via the setValue() method.
So this simple statement will push for us our data.
How to Read/Retrieve Data From Firebase
There are two main ways of reading data from Firebase database:
- Using ChildEventListener – Read and Return data node by node.
- Uisng ValueEventListener – Read all data at once and return it.
The most commonly used way is the ChildEventListener method. However, our app in this case massively suits us to do it the second way, using the ValueEventListener . Why?
Well remember we want to write and read data to firebase then scroll over to the last added item. So we need all the data so that we can only scroll at the end, to the last added item.
So first we create a method called retrieve() . This method will retrieve data and bind to our ListView.
It can also return that data if you want to use it somewhere.
First we need to reference the child node in our database, where our data is stored like a Table:
Then add ValueEventListener to it:
Then pas it an annonymous class that contains our callbacks. These callbacks will handle our events.
The callbacks are:
- onDataChange() – When our data changes, we can read or retrieve the whole list of data at once.
- onCancelled() – When an error is encountered the read operation is cancelled.
To read our data first we will clear the arraylist that will be containing that data:
This avoids duplication.
Then we will check if our data snapshot actually exists and that it has some children. We don’t want to be reading empty space.
Then get the children and actually loop through them:
Inside the loop, for each iteration we will actually read the individual data items via the getValue() method of our DataSnapshot object. Then we pass it the generic class so that it converts it to our POJO:
But we also have to populate the arraylist so that we have the data we will fill our ListView with:
Then outside the loop we will instantiate our adapter. ListView is an adapterview and needs an adapter, especially given we are working with complex data(POJOs).
Then set the adapter to listview via the setAdapter() .
How to Smooth Scroll ListView to Recently Added Firebase Item
To scroll to the last added item in our ListView, we will make our ListView only scroll to the specified adapter position only when the user interface thread is ready.
Othwerwise we risk the scroll not happening as we expect since the user interface is going to be doing alot at this time.
So we use a Handler , a class that residing in the android.os package which can allow us not only to schedule tasks but also enqueue them.
We are interested in this case in the latter, enqueueing. The Handler does this just within the same thread.
So our scroll task will be enqueued and performed only when the UI thread is ready.
How to Use BaseAdapter with Firebase Data
Now that we’ve seen how to fetch firebase data, we need to see how to bind them to a custom listview.
For that we need an adapter. In android there are several adapter implementations.
The most popular and commonly used with Adapterviews like ListView and GridView is the BaseAdapter .
Alot of the other adapters like ArrayAdapter actually derive from this baseadapter .
To use it we extend it:
However, since it’s abstract we’ll need to implement it’s method:
We perform layout inflation and data binding inside the getView() method.
We also listen to our custom listview click events and show the clicked item in a Toast message.
Check the full source code below.
How to Create an Input Form in a Custom Dialog
To actually save data to firebase, that data needs to be typed. Well we need a form where the user types the data.
One way would be to open a new activity to render the form. Another way would be fragment.
Or an even easier way would be to just create a custom dialog that has that form.The dialog can then be invoked or shown when the user clicks the Floating Action Button.
Creating a dialog is very east, you just instantiate the android.app.Dialog class:
Then set the title:
Then what makes it a custom dialog is the fact that we are inflating a custom layout and using it as the content view of the dialog:
Now we can come and listen to save button click events:
After obtaining the values of the EditTexts, we can pass them to our POJO class, then perform basic validation:
To actually save:
Then we refresh the ListView and move to the last saved item.
We agreed, remember that we move to a given adapter position in the ListView by invoking the smoothScrollToPosition() method,passing in the position.
Hey, here’s the full source code of MainActivity.java :
Full Code
Result
Here’s our result, Firebase ListView with CardViews – Write/Save data and Read/Retrieve data and scroll to last saved item.
Issues to Keep in Mind
- If you are getting a java.lang.illegalStateException after following the above steps then it means you have missed a step. This error gets raised if you are trying to access the FirebaseDatabase without initialization.
The most common error is missing to apply the google services plugin or forgetting to register its class path in our app level and project level buil.gradle files respectively.
- Your POJO class must be a standalone class and not an inner class. Otherwise you’ll get errors at runtime that your POJO/Data Object class does not define an empty constructor, even uf it does.
- You must add internet permission in your AndroidManifest.xml or else you cannot make Firebase API calls. Some emulators do not access internet by default, so open up a browser and ensure you can access internet first.
report this ad
Oclemy
Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .
Источник