All CategoriesAndroid App Development

How to Use Free Cloud Database with Android Apps

As we see in Android, there are many options to save and retrieve the data in the database like SQLite, etc. But now we will look at how we can store and sync the data using free cloud database.
There are various cloud providers like Parse, Firebase, AWS Mobile, Kinvey, Buddy, Quickblox, Google App Engine, etc. which provides access to a cloud database, data storage, user management, push notifications and other services.

How to Create a Cloud Database Using Firebase?

Here, we are going to create a cloud database for our Android application using Firebase.
Firebase database is also known as the real-time database. It is used to store and sync the data using Cloud-based NoSQL database.
Inside this, the data is stored in JSON form. We can also sync the data across multiple platforms like Android, iOS, web, etc. from the Firebase database.
Its APIs helps to authenticate users with emails and password. We can also set Read / Write permissions to access the database.
Works in Offline:
Firebase database is supported offline as well. It retains the data easily when back to online. When our device is in offline mode and the new data is stored in the database. After that, when the device back to being online, we can see on the console that the new data will sync automatically. Same will work from console to device also.
Let’s see the whole features of Cloud database using firebase by creating a simple Android application.
Example with Code:
Here, we are going to create Firebase database which shows a list where we can add the new data and perform other operations like update, delete, and store. The data on Firebase database which can be seen from firebase console.

  • Create a new application CloudDatabaseExampleAndroid in Android Studio.
  • Now open Firebase Console and create a new project

  • Now, Add Firebase to your Android App. After this Add App by giving the same package name of your Android application.

  • Next Download the google-services.json file and add this to your app.
  • After creating the project successfully. Click on Authentication and select Sign-In Method from project dashboard. Here, enable the Email/Password provider.

  • Click on Database menu to see the data.

  • Now back to our project, Add the dependencies and create the files to do all operations.

Project level build.gradle File:
Add the dependencies here:

dependencies {
    classpath 'com.google.gms:google-services:3.0.0'
}

App Level build.gradle File:
Add the dependencies here and gradle plugin at the bottom side.

dependencies {
    compile 'com.android.support:design:25.0.0'
    compile 'com.google.firebase:firebase-database:9.4.0'
    compile 'com.google.firebase:firebase-auth:9.4.0'
    compile 'com.google.firebase:firebase-core:9.4.0'
    compile 'com.android.support:recyclerview-v7:25.0.0'
}
apply plugin: 'com.google.gms.google-services'

Requirements:
MainActivity.java, LoginActivity.java, SignupActivity.java, ListItem.java, activity_main.xml, activity_login.xml, activity_signup.xml, list_item.xml, dialog_list_item.xml, menu_main.xml.
Let’s do it one by one in our project.
ListItem.java:
Create this model class for list items that we will add to the database.
Add the code here:

public class ListItem {
    public String listItemText;
    public String listItemCreationDate;
// create its getters and setters
public ListItem(String listItemText) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
    this.listItemCreationDate = sdf.format(new Date());
    this.listItemText = listItemText;
}
@Exclude
public Map<String, Object> toMap() {
    HashMap<String, Object> result = new HashMap<>();
    result.put("listItemText", listItemText);
    result.put("listItemCreationDate", listItemCreationDate);
    return result;
}

toMap() will use for writing the items to the database.
activity_signup.xml:
Create this XML file for the new user.
Add the code here:

<android.support.design.widget.TextInputLayout
        android:id="@+id/signup_input_layout_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp">
        <EditText
            android:id="@+id/ed_SignUP_Input_Email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textEmailAddress"
            android:hint="Email" />
    </android.support.design.widget.TextInputLayout>
    <android.support.design.widget.TextInputLayout
        android:id="@+id/signup_input_layout_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp">
<EditText
             android:id="@+id/ed_SignUP_Input_Password"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:ems="10"
             android:inputType="textPassword"
             android:hint="@string/hint_password" />
     </android.support.design.widget.TextInputLayout>
     <Button android:id="@+id/btn_SignUp"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="@string/btn_sign_up"
         android:background="@color/colorPrimaryDark"
         android:layout_marginTop="40dp"
         android:textColor="@android:color/white"/>
     <Button android:id="@+id/btn_Link_Login"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:text="@string/btn_link_to_login"
         android:background="@android:color/transparent"
         android:layout_marginTop="10dp"
         android:textColor="@color/colorPrimaryDark"/>
 <ProgressBar
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:id="@+id/progressBar"/>

SignupActivity.java:

Here we will initialize the Firebase Auth and create the new user and do other properties like validation etc.
Add the code in onCreate(..){..}:

auth = FirebaseAuth.getInstance();
auth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                Log.d(TAG,"createUserWithEmail:onComplete:" + task.isSuccessful());
                progressBar.setVisibility(View.GONE);
                if (!task.isSuccessful()) {
                    Log.d(TAG,"Authentication failed." + task.getException());
                } else {
                    startActivity(new Intent(SignupActivity.this, MainActivity.class));
                    finish();
                }
            }
        });
Toast.makeText(getApplicationContext(), "You are successfully Registered !!", Toast.LENGTH_SHORT).show();

After successfully registered it will show the user details on a console like this.

Similarly, we can do for Login also, if the user is registered then we can log in it directly to MainActivity.
activity_main.xml:
This is our main layout file. Here it shows the Recycler View and Floating Action Button for adding new data into the database.
Add the code here:

<android.support.design.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="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">
    <android.support.v7.widget.RecyclerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/recycler_view"
        android:scrollbars="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>
<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"
     app:srcCompat="@android:drawable/ic_input_add" />

dialog_list_item.xml: 
Create this file. Here, a dialog appears which takes user input for adding the item in the list.
Add the code here:

<TextView
    android:id="@+id/tv_enterItem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/enter_listItem_text"
    android:layout_gravity="center"
    android:textSize="@dimen/text_size"
    android:textStyle="bold" />
<EditText
    android:id="@+id/ed_DialogUserInput"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

list_item.xml:
Create this XML file for row item.
Add the code here:

<TextView
    android:paddingTop="5dp"
    android:paddingLeft="10dp"
    android:id="@+id/tv_Name"
    android:layout_width="match_parent"
    android:textColor="@android:color/black"
    android:layout_height="wrap_content"
    android:textSize="25dp"
    android:textStyle="bold" />
<View
    android:layout_width="fill_parent"
    android:layout_height="1dp"
    android:layout_below="@+id/tv_Name"
    android:background="@color/colorPrimary"
    android:layout_marginTop="5dp">
</View>

menu_main.xml:
Create this file under menu folder it performs logout and deletes the data actions.
Add the code here:

<item android:id="@+id/action_delete_all"
    android:title="Delete All Items"
    android:orderInCategory="101"
    app:showAsAction="never" />
<item android:id="@+id/action_logout"
    android:title="Logout"
    android:orderInCategory="100"
    app:showAsAction="never" />

MainActivity.java:

This is our Main Activity. Here, we take the reference of RecyclerView and Floating action button which is used to add new item also we take the instance of DatabaseReference using getInstance() method. And perform other functionalities.
Initialize:

DatabaseReference mDatabaseReference;
private RecyclerView mRecyclerView;
private ListItemsAdapter mAdapter;
FloatingActionButton fab;
private ArrayList<ListItem> mListItems;

Add the code in onCreate(..){..}:

mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("listItem");
mListItems = new ArrayList<>();
mRecyclerView = (RecyclerView)findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new ListItemsAdapter(mListItems);
mRecyclerView.setAdapter(mAdapter);
fab = (FloatingActionButton) findViewById(R.id.fab);

Now implements ChildEventListener to retrieve the data and override it’s all callback methods.

mDatabaseReference.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        Log.d(TAG+"Added",dataSnapshot.getValue(ListItem.class).toString());
        ListItem listItem=dataSnapshot.getValue(ListItem.class);
        mListItems.add(listItem);
        mAdapter = new ListItemsAdapter(mListItems);
        mRecyclerView.setAdapter(mAdapter);
    }
    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        Log.d(TAG+"Changed",dataSnapshot.getValue(ListItem.class).toString());
    }
    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {
        Log.d(TAG+"Removed",dataSnapshot.getValue(ListItem.class).toString());
    }
    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        Log.d(TAG+"Moved",dataSnapshot.getValue(ListItem.class).toString());
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.d(TAG+"Cancelled",databaseError.toString());
    }
});

Here, these methods take the actions with their specific events.
onChildAdded(): This method is called when a new item is added to a list and also retrieve the list of items.
onChildChanged(): This method is called if there is any change in the list item. We can use this method to update the list.
onChildRemoved(): This method is called when any item is removed from the list.
onChildMoved(): This method is called for the changes in ordering list.
Create the new list item

final String key = FirebaseDatabase.getInstance().getReference().child("listItem").push().getKey();
LayoutInflater li = LayoutInflater.from(this);
View getListItemView = li.inflate(R.layout.dialog_list_item, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(getListItemView);
final EditText edUserInput = (EditText) getListItemView.findViewById(R.id.ed_DialogUserInput);
// set dialog message
alertDialogBuilder
        .setCancelable(false)
        .setPositiveButton("OK",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                // get user input and set it to result
                // edit text
                String listItemText = edUserInput.getText().toString();
                ListItem listItem = new ListItem(listItemText);
                Map<String, Object> listItemValues = listItem.toMap();
                Map<String, Object> childUpdates = new HashMap<>();
                childUpdates.put("/listItem/" + key, listItemValues);
                FirebaseDatabase.getInstance().getReference().updateChildren(childUpdates);
            }
        }).create()
        .show();

Here we create a new key by using push().getKey() method also use toMap() method to create map of items and add it into firebase database by using updateChildren() method.
Delete the items from the list

FirebaseDatabase.getInstance().getReference().child("listItem").removeValue();
mListItems.clear();
mAdapter.notifyDataSetChanged();
Toast.makeText(this,"Items Deleted Successfully",Toast.LENGTH_SHORT).show();

By using removeValue() method of Firebase Database we can delete the list items.
We can also Add, Delete, Update the items from Firebase console and update the list accordingly in our Android application.

Download Source Code: GitHub

Conclusion:

This is the simple example of a free Cloud Database as I discussed above here by using Firebase database. We can easily create the database in our Android application and store the data. We can also add one or more users to access the database and following Firebase security and rules we can allow everyone to read and write data without authentication and data validation. If there is any change in data, then it gets reflected in all the platforms and devices by performing synchronization. So overall, this is one of the best ways to use free cloud database in Android, and is of great importance for Android development.
Output:

Before Login

After Login adding Item

Item Added

Data on Console

Before Delete

After Delete

Enroll for Android Developer Training conducted by Acadgild and become a successful Android Developer.
Keep visiting acadgild.com for more updates on the technical and certification courses.
 

3 Comments

  1. Dear Sir,
    The two java java files ExampleInstrumentedTest and ExampleUnitTest are not compiling and showing may errors as org.junit, orgjrunner, etc does not exits.
    Kindly help

  2. I needa have basic notions to start creating a database where are present texts, photos and video to link with my Android App so that I have all on my smartphone, and when I needa update it, let I can and automatically on my phone it’s updated too

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close
Close