Bitbucket Clone Link : git clone https://bitbucket.org/josephbill/kotlincrud.git

Firebase is a mobile and web application development platform developed by Firebase, Inc. in 2011, then acquired by Google in 2014. As of March 2020, the Firebase platform has 19 products, which are used by more than 1.5 million apps

Firebase provides us with many Cloud Services which we can use to speed up our development process and implement relatively time consuming features much faster. For example in this tutorial I will use:

Real Time Database

This article is a technical walk-through on how to implement the Create (Insert) functionality using the Firebase Real Time Database feature.

Steps

  1. Create a new Android Studio project called FirebaseCRUD

2. Once the project is built,
-> go to the tools tab
-> select Firebase and in the Firebase assistant panel that opens connect to the Firebase real-time database
-> Create a new project in the dialog that pops up

This is one way of creating a project in Firebase


You can create a project directly from the Firebase console by going to this link firebase.google.com, sign in using your google account , once signed in , select the go to console option , once logged in to the console, select the android icon and create a new project by following the default instructions, note the google-services.json package and where it is to be placed in your project structure .You can connect to this project in your android studio by following the android studio steps mentioned in this step 2. On the dialog box instead of creating a project , select your project

name the project
select continue
hit create project
click the android icon to connect project in console to your android studio project

Now we have the firebase set up ,let's create the project

CREATE' Operation

3. Our sample application saves the ratings of various heroes , so in our android studio project , activity_main.xml we we are going to have an edit text , an image upload link which will show you how to pick an image from a gallery , a rating bar and a submit button.

code

<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
    android:background="#E9EEEF"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    
    <EditText
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="40dp"
    android:inputType="textPersonName"
    android:text="Name" />

<RatingBar
    android:id="@+id/rating"
    android:layout_below="@+id/name"
    android:padding="20dp"
    android:max="5"
    android:stepSize="1"
    android:layout_centerHorizontal="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<ImageView
    android:layout_width="140dp"
    android:layout_height="140dp"
    android:src="@drawable/ic_launcher_background"
    android:layout_below="@+id/rating"
    android:layout_centerHorizontal="true"
    android:id="@+id/imageUpload"
    />

<Button
    android:id="@+id/btnsave"
    android:layout_width="wrap_content"
    android:background="#000"
    android:textColor="#fff"
    android:layout_height="wrap_content"
    android:textStyle="bold"
    android:layout_marginTop="10dp"
    android:layout_below="@+id/imageUpload"
    android:layout_centerHorizontal="true"
    android:text="Submit" />


<ListView
    android:id="@+id/listView"
    android:layout_below="@+id/btnsave"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
    
    </RelativeLayout>

4. The next step is to go to the MainActivity.kt file to declare and initialize our User Interface objects and also set up the call for the method that will save our data to the Firebase real-time database .

//declare the ui elements
lateinit var editName: EditText
lateinit var ratings: RatingBar
lateinit var submit: Button
lateinit var imageClick: ImageView
private val RequestCode = 438
//image uri
private var imageUri: Uri? = null

we will also set up the declaration of our firebase database reference and our storage bucket reference : firebase stores text data in the Realtime database and image objects in the storage bucket reference

//database reference

lateinit var ref: DatabaseReference
//firebase storage reference
private var storageRef: StorageReference? = null

..... we also need a mutable list to store our user data in

//declaring a mutable list to store my list of heroes

lateinit var heroList: MutableList<Hero>

5. The next step is to move on to the onCreate lifecycle method and below the setContentView function we will call a method that will initialize our views object and create our database reference

 //create a firebase database reference object : here we use the getReference to create a new
        //firebase node file in our database , i will call mine heroes


        //realtime database reference for text data
        ref = FirebaseDatabase.getInstance().getReference("heroes")
        //storage database reference for image uploads to the firebase storage bucket
        storageRef = FirebaseStorage.getInstance().reference.child("heroes")
           
        //method name 
        intialise()

proceed to create this method outside the onCreate lifecycle method

//code
private fun intialise() {
//link views
editName = findViewById(R.id.name)
ratings = findViewById(R.id.rating)
submit = findViewById(R.id.btnsave)

       //intialise the heroes list
       heroList = mutableListOf()

       //set up a method for selecting an image
       imageClick!!.setOnClickListener{
        pickImage()
    }
    //when submit button is hit this is the method that will be used to save our heroes data in the //database
    submit!!.setOnClickListener{
        saveRating()
    }

}

6. In-order to save the data to the firebase Realtime database we need an object class.
create a new Kotlin class called Hero that will create the model for our storage

class Hero (val id: String,val name: String, val rating: Int){
//constructor
constructor() : this("","",0){

         }
         
 }

7. Now we can use the database reference to save values, we need to create a unique node file in the parent node file in the getreference on step 5 , using the saveRating() method , create an instance of the hero object inside the MainActivity class and pass the values as per the Hero object template constructor

First add code block to the pickImage() method , here we need to be able to connect to the user's phone gallery to enable them to pick an image

a) go to the AndroidManifest File in the manifest package and add this permissions after the manifest opening tag

//to connect to internet

<uses-permission android:name="android.permission.INTERNET"/>
// connect to wifi networks
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
//access users network state 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 //access device write permission for  external storage 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 //access device read permission for external storage 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

//pickImage method

    private fun pickImage() {
    val intent = Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
    startActivityForResult(intent, RequestCode)

}

//onActivityResult method for image

//onactivity result for image
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if(requestCode == RequestCode && resultCode == Activity.RESULT_OK && data!!.data != null){
  
    }
}

Method to save hero rating and name to my firebase Realtime database

//save rating

   //method to save rating to my firebase realtime database
    private fun saveRating() {
        //getting the text input
        val username = editName.text.toString().trim()
        //validating entry
        if (username.isEmpty()){
            editName.error = "please enter a name to rate"
            return
        }



        //creating a unique node in the getreference node that will enable us to push our hero object
        //to the database reference
        //this step will ensure for each record inserted the database generates a new key
        val heroId = ref.push().key

        //my hero object
        val hero = heroId?.let { Hero(it,username,ratings.rating.toInt())}
        //pushing my hero object to my database reference , surrounding with null check to prevent errors
        //this will save our hero to our firebase database
        if (heroId != null) {
            ref.child(heroId).setValue(hero).addOnCompleteListener{
                Toast.makeText(applicationContext,"Hero rated successfully",Toast.LENGTH_LONG).show()
            }
        }


    }
open the project in the firebase console , go to database , realtime database , select the rules pane and make the access public , to enable anyone to make write to the database, but dont make it public for products in production cause ideally u will have an authentication process

to change the rules to public equal everything to true 

You can build and run the app for testing the Create Operation check the result in the firebase console Realtime Database section.

sample submission

In computer programming, create is one of the four basic functions(others are read,update and delete) of persistent storage.

The next steps in this article will be to implement the READ, UPDATE And Delete functionalities to complete the CRUD system.

Happy Coding!!

You've successfully subscribed to Decoded For Devs
Welcome back! You've successfully signed in.
Great! You've successfully signed up.
Your link has expired
Success! Your account is fully activated, you now have access to all content.