User Authentication and CRUD Operation with Firebase Realtime Database in Android

10 Jan, 2022
Firebase is a famous product of Google which is used by so many developers to add backend functionality for their website as well as apps. The Firebase will make your job really easier for the backend database and handling the database. In this article, we will take a look at the implementation of the Firebase Realtime Database in Android. In this article, we will be adding an Email and password authentication inside our app and along with that, we will be performing the CRUD (Create, Read, Update and Delete) operations inside our application using the Firebase Realtime Database. 
https://www.youtube.com/watch?v=-Gvpf8tXpbc
In this article, we will be building a simple Android Application in which we will be firstly authenticating the user with their email and password. After that, we will display the list of courses that are available on Geeks for Geeks in the recycler view. We will be able to perform CRUD operations on these courses. Below is the video in which we will get to see what we are going to build in this article. 
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 Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now 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 Realtime database has been added to our Gradle file. Now navigate to the app > Gradle Scripts and inside that file check whether the below dependency is added or not. If the below dependency is not added in your build.gradle file. Add the below dependency in the dependencies section. Below is the complete dependencies section in which there are dependencies for authentication as well as the database. 
dependencies {
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.4.0'
    // dependency for picasso for loading image from url 
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    // dependency for firebase database. 
    implementation 'com.google.firebase:firebase-database:20.0.0'
    implementation platform('com.google.firebase:firebase-bom:28.2.1')
    // dependency for firebase authentication. 
    implementation 'com.google.firebase:firebase-auth'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
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 Adding Firebase to Android App.  
Step 3: Creating 4 different empty activities
Navigate to the app > Your app’s package name > Right-click on it > New > Activity > Select Empty Activity and Create a New Activity. Below is the name for the four different activities which we have to pass while creating new activities. 
AddCourseActivity: This activity we will use for adding a new Course.
EditCourseActivity: This activity will be used to edit our course as well as delete our course.
LoginActivity: This activity will be used for Login purposes for existing user login.
RegisterActivity: This activity is used for the registration of new Users.
MainActivity.java file will be already present in which we will be displaying the list of courses in RecyclerView. 
Step 4: Working with AndroidManifest.xml file
Navigate to app > AndroidManifest.xml file and add internet permissions to it. Below is the complete code for the AndroidManifest.xml file. Inside this file, we are also changing our launcher activity to Login Activity. Comments are added in the code to get to know in more detail. 
XML
<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.gtappdevelopers.firebasecrudapp">     <!--permissions for internet-->    <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />     <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/Theme.FirebaseCrudApp">        <activity            android:name=".EditCourseActivity"            android:label="Edit Course" />        <activity            android:name=".AddCourseActivity"            android:label="Add Course" />        <activity            android:name=".RegisterActivity"            android:label="Register" />        <!--login activity is set as launcher activity-->        <activity android:name=".LoginActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name=".MainActivity" />    </application> </manifest>
 Step 5: Updating colors.xml file
Navigate to the app > res > values > colors.xml and add the below colors to it. 
XML
<?xml version="1.0" encoding="utf-8"?><resources xmlns:tools="http://schemas.android.com/tools">    <color name="purple_200">#296D98</color>    <color name="purple_500">#296D98</color>    <color name="purple_700">#296D98</color>    <color name="teal_200">#FF03DAC5</color>    <color name="teal_700">#FF018786</color>    <color name="black">#FF000000</color>    <color name="white">#FFFFFFFF</color>     <color name="black_shade_1">#0e2433</color>    <color name="black_shade_2">#1C4966</color>     <color name="black_shade_3">#22252D</color>    <color name="mtrl_textinput_default_box_stroke_color" tools:override="true">#296D98</color>     <color name="light_blue_shade_1">#296D98</color>    <color name="gray">#424242</color>    <color name="yellow">#ffa500</color>    <color name="dark_blue_shade">#0D2162</color>    <color name="dark_blue_shade_2">#17388E</color>    <color name="light_blue_shade">#12B2E6</color> </resources>
 Step 6: Updating our themes.xml file 
Navigate to the app > res > values > themes.xml and add the below code to it. 
XML
<resources xmlns:tools="http://schemas.android.com/tools">    <!-- Base application theme. -->    <style name="Theme.FirebaseCrudApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">        <!-- Primary brand color. -->        <item name="colorPrimary">@color/purple_500</item>        <item name="colorPrimaryVariant">@color/purple_700</item>        <item name="colorOnPrimary">@color/white</item>        <!-- Secondary brand color. -->        <item name="colorSecondary">@color/teal_200</item>        <item name="colorSecondaryVariant">@color/teal_700</item>        <item name="colorOnSecondary">@color/black</item>        <!-- Status bar color. -->        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>        <!-- Customize your theme here. -->    </style>     <style name="AppBottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog">        <item name="bottomSheetStyle">@style/AppModalStyle</item>    </style>     <style name="BottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog">        <item name="bottomSheetStyle">@style/BottomSheetStyle</item>    </style>     <style name="BottomSheetStyle" parent="Widget.Design.BottomSheet.Modal">        <item name="android:background">@android:color/transparent</item>    </style>     <style name="AppModalStyle" parent="Widget.Design.BottomSheet.Modal">        <item name="android:background">@drawable/rounded_drawable</item>    </style>     <style name="LoginTextInputLayoutStyle" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">        <item name="boxStrokeColor">#296D98</item>        <item name="boxStrokeWidth">1dp</item>    </style>  </resources>
 Step 7: Creating a custom background for our button and custom progress bar background
Navigate to the app > res > drawable > Right-click on it > New Drawable Resource file and name it as button_back and add below code to it. Comments are added in the code to get to know in detail. 
XML
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle">    <!--for specifying corner radius-->    <corners android:radius="20dp" />    <!-- for specifying solid color-->    <solid android:color="@color/black_shade_1" /> </shape>
 Navigate to the app > res > drawable > Right-click on it > New Drawable Resource file and name it as progress_back and add the below code to it. Comments are added in the code to get to know in detail. 
XML
<?xml version="1.0" encoding="utf-8"?><rotate    xmlns:android="http://schemas.android.com/apk/res/android"    android:fromDegrees="0"    android:pivotX="50%"    android:pivotY="50%"    android:toDegrees="360">     <!--shape tag is used to        build a shape in XML-->    <shape        android:innerRadiusRatio="3"        android:shape="ring"        android:thicknessRatio="8"        android:useLevel="false">         <!--set the size of the shape-->        <size            android:width="76dip"            android:height="76dip" />         <!--set the color gradients            of the shape-->        <gradient            android:angle="0"            android:endColor="#00ffffff"            android:startColor="@color/purple_200"            android:type="sweep"            android:useLevel="false" />    </shape> </rotate>
 Step 8: Working with activity_register.xml file
Navigate to the app > res > activity_register.xml and add the below code to it. Comments are added in the code to get to know in more detail. 
XML
<?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:layout_height="match_parent"    android:background="@color/black_shade_1"    tools:context=".RegisterActivity">     <!--edit text for user name-->    <com.google.android.material.textfield.TextInputLayout        android:id="@+id/idTILUserName"        style="@style/LoginTextInputLayoutStyle"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginStart="20dp"        android:layout_marginTop="140dp"        android:layout_marginEnd="20dp"        android:hint="Enter User Name"        android:padding="5dp"        android:textColorHint="@color/white"        app:hintTextColor="@color/white">         <com.google.android.material.textfield.TextInputEditText            android:id="@+id/idEdtUserName"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:ems="10"            android:importantForAutofill="no"            android:inputType="textEmailAddress"            android:textColor="@color/white"            android:textColorHint="@color/white"            android:textSize="14sp" />    </com.google.android.material.textfield.TextInputLayout>     <!--edit text for user password-->    <com.google.android.material.textfield.TextInputLayout        android:id="@+id/idTILPassword"        style="@style/LoginTextInputLayoutStyle"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idTILUserName"        android:layout_marginStart="20dp"        android:layout_marginTop="20dp"        android:layout_marginEnd="20dp"        android:hint="Enter Your Password"        android:padding="5dp"        android:textColorHint="@color/white"        app:hintTextColor="@color/white">         <com.google.android.material.textfield.TextInputEditText            android:id="@+id/idEdtPassword"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:ems="10"            android:importantForAutofill="no"            android:inputType="textPassword"            android:textColor="@color/white"            android:textColorHint="@color/white"            android:textSize="14sp" />    </com.google.android.material.textfield.TextInputLayout>     <!--edit text for confirmation of user password-->     <com.google.android.material.textfield.TextInputLayout        android:id="@+id/idTILConfirmPassword"        style="@style/LoginTextInputLayoutStyle"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idTILPassword"        android:layout_marginStart="20dp"        android:layout_marginTop="20dp"        android:layout_marginEnd="20dp"        android:hint="Confirm Your Password"        android:padding="5dp"        android:textColorHint="@color/white"        app:hintTextColor="@color/white">         <com.google.android.material.textfield.TextInputEditText            android:id="@+id/idEdtConfirmPassword"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:ems="10"            android:importantForAutofill="no"            android:inputType="textPassword"            android:textColor="@color/white"            android:textColorHint="@color/white"            android:textSize="14sp" />    </com.google.android.material.textfield.TextInputLayout>     <!--button for creating user account.-->    <Button        android:id="@+id/idBtnRegister"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idTILConfirmPassword"        android:layout_marginStart="25dp"        android:layout_marginTop="40dp"        android:layout_marginEnd="25dp"        android:background="@drawable/button_back"        android:text="Register"        android:textAllCaps="false" />     <!--text view for displaying a text on        clicking we will open a login page-->    <TextView        android:id="@+id/idTVLoginUser"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idBtnRegister"        android:layout_marginTop="40dp"        android:gravity="center"        android:padding="10dp"        android:text="Already a User ? Login Here"        android:textAlignment="center"        android:textAllCaps="false"        android:textColor="@color/white"        android:textSize="18sp" />     <!--progress bar as a loading indicator-->    <ProgressBar        android:id="@+id/idPBLoading"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:indeterminate="true"        android:indeterminateDrawable="@drawable/progress_back"        android:visibility="gone" /> </RelativeLayout>
 Step 9: Working with RegisterActivity.java file
Navigate to the app > java > your app’s package name > RegisterActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. 
Java
package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.android.material.textfield.TextInputEditText;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth; public class RegisterActivity extends AppCompatActivity {     // creating variables for edit text and textview,    // firebase auth, button and progress bar.    private TextInputEditText userNameEdt, passwordEdt, confirmPwdEdt;    private TextView loginTV;    private Button registerBtn;    private FirebaseAuth mAuth;    private ProgressBar loadingPB;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_register);                 // initializing all our variables.        userNameEdt = findViewById(R.id.idEdtUserName);        passwordEdt = findViewById(R.id.idEdtPassword);        loadingPB = findViewById(R.id.idPBLoading);        confirmPwdEdt = findViewById(R.id.idEdtConfirmPassword);        loginTV = findViewById(R.id.idTVLoginUser);        registerBtn = findViewById(R.id.idBtnRegister);        mAuth = FirebaseAuth.getInstance();         // adding on click for login tv.        loginTV.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // opening a login activity on clicking login text.                Intent i = new Intent(RegisterActivity.this, LoginActivity.class);                startActivity(i);            }        });                 // adding click listener for register button.        registerBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // hiding our progress bar.                loadingPB.setVisibility(View.VISIBLE);                 // getting data fro =m our edit text.                String userName = userNameEdt.getText().toString();                String pwd = passwordEdt.getText().toString();                String cnfPwd = confirmPwdEdt.getText().toString();                 // checking if the password and confirm password is equal or not.                if (!pwd.equals(cnfPwd)) {                    Toast.makeText(RegisterActivity.this, "Please check both having same password..", Toast.LENGTH_SHORT).show();                } else if (TextUtils.isEmpty(userName) && TextUtils.isEmpty(pwd) && TextUtils.isEmpty(cnfPwd)) {                     // checking if the text fields are empty or not.                    Toast.makeText(RegisterActivity.this, "Please enter your credentials..", Toast.LENGTH_SHORT).show();                } else {                     // on below line we are creating a new user by passing email and password.                    mAuth.createUserWithEmailAndPassword(userName, pwd).addOnCompleteListener(new OnCompleteListener<AuthResult>() {                        @Override                        public void onComplete(@NonNull Task<AuthResult> task) {                            // on below line we are checking if the task is success or not.                            if (task.isSuccessful()) {                                 // in on success method we are hiding our progress bar and opening a login activity.                                loadingPB.setVisibility(View.GONE);                                Toast.makeText(RegisterActivity.this, "User Registered..", Toast.LENGTH_SHORT).show();                                Intent i = new Intent(RegisterActivity.this, LoginActivity.class);                                startActivity(i);                                finish();                            } else {                                 // in else condition we are displaying a failure toast message.                                loadingPB.setVisibility(View.GONE);                                Toast.makeText(RegisterActivity.this, "Fail to register user..", Toast.LENGTH_SHORT).show();                            }                        }                    });                }            }        });    }}
 Step 10: Working with activity_login.xml file
Navigate to the app > res > activity_login.xml and add the below code to it. Comments are added in the code to get to know in more detail. 
XML
<?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:layout_height="match_parent"    android:background="@color/black_shade_1"    tools:context=".LoginActivity">     <!--edit text for user name-->    <com.google.android.material.textfield.TextInputLayout        android:id="@+id/idTILUserName"        style="@style/LoginTextInputLayoutStyle"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginStart="20dp"        android:layout_marginTop="140dp"        android:layout_marginEnd="20dp"        android:hint="Enter User Name"        android:padding="5dp"        android:textColorHint="@color/white"        app:hintTextColor="@color/white">         <com.google.android.material.textfield.TextInputEditText            android:id="@+id/idEdtUserName"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:ems="10"            android:importantForAutofill="no"            android:inputType="textEmailAddress"            android:textColor="@color/white"            android:textColorHint="@color/white"            android:textSize="14sp" />    </com.google.android.material.textfield.TextInputLayout>     <!--edit text for password-->    <com.google.android.material.textfield.TextInputLayout        android:id="@+id/idTILPassword"        style="@style/LoginTextInputLayoutStyle"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idTILUserName"        android:layout_marginStart="20dp"        android:layout_marginTop="40dp"        android:layout_marginEnd="20dp"        android:hint="Enter your Password"        android:padding="5dp"        android:textColorHint="@color/white"        app:hintTextColor="@color/white">         <com.google.android.material.textfield.TextInputEditText            android:id="@+id/idEdtPassword"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:ems="10"            android:importantForAutofill="no"            android:inputType="textPassword"            android:textColor="@color/white"            android:textColorHint="@color/white"            android:textSize="14sp" />    </com.google.android.material.textfield.TextInputLayout>     <!--button for login-->    <Button        android:id="@+id/idBtnLogin"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idTILPassword"        android:layout_marginStart="25dp"        android:layout_marginTop="40dp"        android:layout_marginEnd="25dp"        android:background="@drawable/button_back"        android:text="Login"        android:textAllCaps="false"        />     <!--text view for creating a new account-->    <TextView        android:id="@+id/idTVNewUser"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idBtnLogin"        android:layout_marginTop="40dp"        android:gravity="center"        android:padding="10dp"        android:text="New User ? Register Here"        android:textAlignment="center"        android:textAllCaps="false"        android:textColor="@color/white"        android:textSize="18sp" />     <!--progress-bar for loading indicator-->    <ProgressBar        android:id="@+id/idPBLoading"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@id/idTVNewUser"        android:layout_centerHorizontal="true"        android:layout_marginTop="10dp"        android:indeterminate="true"        android:indeterminateDrawable="@drawable/progress_back"        android:visibility="gone" /> </RelativeLayout>
 Step 11: Working with LoginActivity.java file
Navigate to the app > java > your app’s package name > LoginActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. 
Java
package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.Task;import com.google.android.material.textfield.TextInputEditText;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.auth.FirebaseUser; public class LoginActivity extends AppCompatActivity {     // creating variable for edit text, textview,    // button, progress bar and firebase auth.    private TextInputEditText userNameEdt, passwordEdt;    private Button loginBtn;    private TextView newUserTV;    private FirebaseAuth mAuth;    private ProgressBar loadingPB;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_login);        // initializing all our variables.        userNameEdt = findViewById(R.id.idEdtUserName);        passwordEdt = findViewById(R.id.idEdtPassword);        loginBtn = findViewById(R.id.idBtnLogin);        newUserTV = findViewById(R.id.idTVNewUser);        mAuth = FirebaseAuth.getInstance();        loadingPB = findViewById(R.id.idPBLoading);        // adding click listener for our new user tv.        newUserTV.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // on below line opening a login activity.                Intent i = new Intent(LoginActivity.this, RegisterActivity.class);                startActivity(i);            }        });         // adding on click listener for our login button.        loginBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // hiding our progress bar.                loadingPB.setVisibility(View.VISIBLE);                // getting data from our edit text on below line.                String email = userNameEdt.getText().toString();                String password = passwordEdt.getText().toString();                // on below line validating the text input.                if (TextUtils.isEmpty(email) && TextUtils.isEmpty(password)) {                    Toast.makeText(LoginActivity.this, "Please enter your credentials..", Toast.LENGTH_SHORT).show();                    return;                }                // on below line we are calling a sign in method and passing email and password to it.                mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {                    @Override                    public void onComplete(@NonNull Task<AuthResult> task) {                        // on below line we are checking if the task is success or not.                        if (task.isSuccessful()) {                            // on below line we are hiding our progress bar.                            loadingPB.setVisibility(View.GONE);                            Toast.makeText(LoginActivity.this, "Login Successful..", Toast.LENGTH_SHORT).show();                            // on below line we are opening our mainactivity.                            Intent i = new Intent(LoginActivity.this, MainActivity.class);                            startActivity(i);                            finish();                        } else {                            // hiding our progress bar and displaying a toast message.                            loadingPB.setVisibility(View.GONE);                            Toast.makeText(LoginActivity.this, "Please enter valid user credentials..", Toast.LENGTH_SHORT).show();                        }                    }                });            }        });    }     @Override    protected void onStart() {        super.onStart();        // in on start method checking if        // the user is already sign in.        FirebaseUser user = mAuth.getCurrentUser();        if (user != null) {            // if the user is not null then we are              // opening a main activity on below line.            Intent i = new Intent(LoginActivity.this, MainActivity.class);            startActivity(i);            this.finish();        }    }}
  Step 12: Creating a Modal class for our data to be displayed inside our RecyclerView
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseRVModal and add the below code to it. Comments are added in the code to get to know in more detail. 
Java
package com.gtappdevelopers.firebasecrudapp; import android.os.Parcel;import android.os.Parcelable; public class CourseRVModal implements Parcelable {    // creating variables for our different fields.    private String courseName;    private String courseDescription;    private String coursePrice;    private String bestSuitedFor;    private String courseImg;    private String courseLink;    private String courseId;      public String getCourseId() {        return courseId;    }     public void setCourseId(String courseId) {        this.courseId = courseId;    }      // creating an empty constructor.    public CourseRVModal() {     }     protected CourseRVModal(Parcel in) {        courseName = in.readString();        courseId = in.readString();        courseDescription = in.readString();        coursePrice = in.readString();        bestSuitedFor = in.readString();        courseImg = in.readString();        courseLink = in.readString();    }     public static final Creator<CourseRVModal> CREATOR = new Creator<CourseRVModal>() {        @Override        public CourseRVModal createFromParcel(Parcel in) {            return new CourseRVModal(in);        }         @Override        public CourseRVModal[] newArray(int size) {            return new CourseRVModal[size];        }    };     // creating getter and setter methods.    public String getCourseName() {        return courseName;    }     public void setCourseName(String courseName) {        this.courseName = courseName;    }     public String getCourseDescription() {        return courseDescription;    }     public void setCourseDescription(String courseDescription) {        this.courseDescription = courseDescription;    }     public String getCoursePrice() {        return coursePrice;    }     public void setCoursePrice(String coursePrice) {        this.coursePrice = coursePrice;    }     public String getBestSuitedFor() {        return bestSuitedFor;    }     public void setBestSuitedFor(String bestSuitedFor) {        this.bestSuitedFor = bestSuitedFor;    }     public String getCourseImg() {        return courseImg;    }     public void setCourseImg(String courseImg) {        this.courseImg = courseImg;    }     public String getCourseLink() {        return courseLink;    }     public void setCourseLink(String courseLink) {        this.courseLink = courseLink;    }      public CourseRVModal(String courseId, String courseName, String courseDescription, String coursePrice, String bestSuitedFor, String courseImg, String courseLink) {        this.courseName = courseName;        this.courseId = courseId;        this.courseDescription = courseDescription;        this.coursePrice = coursePrice;        this.bestSuitedFor = bestSuitedFor;        this.courseImg = courseImg;        this.courseLink = courseLink;    }     @Override    public int describeContents() {        return 0;    }     @Override    public void writeToParcel(Parcel dest, int flags) {        dest.writeString(courseName);        dest.writeString(courseId);        dest.writeString(courseDescription);        dest.writeString(coursePrice);        dest.writeString(bestSuitedFor);        dest.writeString(courseImg);        dest.writeString(courseLink);    }}
 
 Step 13: Working with activity_add_course.xml file
Navigate to the app > res > layout > activity_add_course.xml and add the below code to it. Comments are added in the code to get to know in more detail. 
XML
<?xml version="1.0" encoding="utf-8"?><ScrollView    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:layout_height="match_parent"    android:background="@color/black_shade_1"    tools:context=".AddCourseActivity">     <RelativeLayout        android:layout_width="match_parent"        android:layout_height="wrap_content">         <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="vertical">             <!--edit text for course name-->            <com.google.android.material.textfield.TextInputLayout                android:id="@+id/idTILCourseName"                style="@style/LoginTextInputLayoutStyle"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_marginLeft="10dp"                android:layout_marginTop="10dp"                android:layout_marginRight="10dp"                android:hint="Enter Course Name"                android:padding="5dp"                android:textColorHint="@color/white"                app:hintTextColor="@color/white">                 <com.google.android.material.textfield.TextInputEditText                    android:id="@+id/idEdtCourseName"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:ems="10"                    android:importantForAutofill="no"                    android:inputType="textImeMultiLine|textMultiLine"                    android:textColor="@color/white"                    android:textColorHint="@color/white"                    android:textSize="14sp" />            </com.google.android.material.textfield.TextInputLayout>             <!--edit text for course price-->            <com.google.android.material.textfield.TextInputLayout                android:id="@+id/idTILCoursePrice"                style="@style/LoginTextInputLayoutStyle"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_marginLeft="10dp"                android:layout_marginTop="10dp"                android:layout_marginRight="10dp"                android:hint="Enter Course Price"                android:padding="5dp"                android:textColorHint="@color/white"                app:boxStrokeColor="@color/purple_200"                app:hintTextColor="@color/white">                 <com.google.android.material.textfield.TextInputEditText                    android:id="@+id/idEdtCoursePrice"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:ems="10"                    android:importantForAutofill="no"                    android:inputType="phone"                    android:textColor="@color/white"                    android:textColorHint="@color/white"                    android:textSize="14sp"                    app:boxStrokeColor="@color/purple_200" />            </com.google.android.material.textfield.TextInputLayout>             <!--edit text for course suited for-->            <com.google.android.material.textfield.TextInputLayout                android:id="@+id/idTILCourseSuitedFor"                style="@style/LoginTextInputLayoutStyle"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_marginLeft="10dp"                android:layout_marginTop="10dp"                android:layout_marginRight="10dp"                android:hint="Enter Course Suited For"                android:padding="5dp"                android:textColorHint="@color/white"                app:hintTextColor="@color/white">                 <com.google.android.material.textfield.TextInputEditText                    android:id="@+id/idEdtSuitedFor"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:ems="10"                    android:importantForAutofill="no"                    android:inputType="textImeMultiLine|textMultiLine"                    android:textColor="@color/white"                    android:textColorHint="@color/white"                    android:textSize="14sp" />            </com.google.android.material.textfield.TextInputLayout>             <!--edit text for course image link-->            <com.google.android.material.textfield.TextInputLayout                android:id="@+id/idTILCourseImageLink"                style="@style/LoginTextInputLayoutStyle"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_marginLeft="10dp"                android:layout_marginTop="10dp"                android:layout_marginRight="10dp"                android:hint="Enter Course Image Link"                android:padding="5dp"                android:textColorHint="@color/white"                app:hintTextColor="@color/white">                 <com.google.android.material.textfield.TextInputEditText                    android:id="@+id/idEdtCourseImageLink"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:ems="10"                    android:importantForAutofill="no"                    android:inputType="textImeMultiLine|textMultiLine"                    android:textColor="@color/white"                    android:textColorHint="@color/white"                    android:textSize="14sp" />            </com.google.android.material.textfield.TextInputLayout>             <!--edit text for course link-->            <com.google.android.material.textfield.TextInputLayout                android:id="@+id/idTILCourseLink"                style="@style/LoginTextInputLayoutStyle"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_marginLeft="10dp"                android:layout_marginTop="10dp"                android:layout_marginRight="10dp"                android:hint="Enter Course Link"                android:padding="5dp"                android:textColorHint="@color/white"                app:hintTextColor="@color/white">                 <com.google.android.material.textfield.TextInputEditText                    android:id="@+id/idEdtCourseLink"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:ems="10"                    android:importantForAutofill="no"                    android:inputType="textImeMultiLine|textMultiLine"                    android:textColor="@color/white"                    android:textColorHint="@color/white"                    android:textSize="14sp" />            </com.google.android.material.textfield.TextInputLayout>              <!--edit text for course description-->            <com.google.android.material.textfield.TextInputLayout                android:id="@+id/idTILCourseDescription"                style="@style/LoginTextInputLayoutStyle"                android:layout_width="match_parent"                android:layout_height="200dp"                android:layout_marginLeft="10dp"                android:layout_marginTop="10dp"                android:layout_marginRight="10dp"                android:hint="Enter Course Description"                android:padding="5dp"                android:textColorHint="@color/white"                app:hintTextColor="@color/white">                 <com.google.android.material.textfield.TextInputEditText                    android:id="@+id/idEdtCourseDescription"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:ems="10"                    android:importantForAutofill="no"                    android:inputType="textImeMultiLine|textMultiLine"                    android:textColor="@color/white"                    android:textColorHint="@color/white"                    android:textSize="14sp" />            </com.google.android.material.textfield.TextInputLayout>             <!--button for adding a new course-->            <Button                android:id="@+id/idBtnAddCourse"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_marginStart="10dp"                android:layout_marginTop="10dp"                android:layout_marginEnd="10dp"                android:layout_marginBottom="10dp"                android:background="@drawable/button_back"                android:text="Add Your Course"                android:textAllCaps="false" />          </LinearLayout>         <!--progress bar for loading indicator-->        <ProgressBar            android:id="@+id/idPBLoading"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:layout_gravity="center"            android:indeterminate="true"            android:indeterminateDrawable="@drawable/progress_back"            android:visibility="gone" />     </RelativeLayout></ScrollView>
 Step 14: Working with the AddCourseActivity.java file
Navigate to the app > java > your app’s package name > AddCourseActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. 
Java
package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.textfield.TextInputEditText;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; public class AddCourseActivity extends AppCompatActivity {     // creating variables for our button, edit text,    // firebase database, database reference, progress bar.    private Button addCourseBtn;    private TextInputEditText courseNameEdt, courseDescEdt, coursePriceEdt, bestSuitedEdt, courseImgEdt, courseLinkEdt;    FirebaseDatabase firebaseDatabase;    DatabaseReference databaseReference;    private ProgressBar loadingPB;    private String courseID;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_add_course);        // initializing all our variables.        addCourseBtn = findViewById(R.id.idBtnAddCourse);        courseNameEdt = findViewById(R.id.idEdtCourseName);        courseDescEdt = findViewById(R.id.idEdtCourseDescription);        coursePriceEdt = findViewById(R.id.idEdtCoursePrice);        bestSuitedEdt = findViewById(R.id.idEdtSuitedFor);        courseImgEdt = findViewById(R.id.idEdtCourseImageLink);        courseLinkEdt = findViewById(R.id.idEdtCourseLink);        loadingPB = findViewById(R.id.idPBLoading);        firebaseDatabase = FirebaseDatabase.getInstance();        // on below line creating our database reference.        databaseReference = firebaseDatabase.getReference("Courses");        // adding click listener for our add course button.        addCourseBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                loadingPB.setVisibility(View.VISIBLE);                // getting data from our edit text.                String courseName = courseNameEdt.getText().toString();                String courseDesc = courseDescEdt.getText().toString();                String coursePrice = coursePriceEdt.getText().toString();                String bestSuited = bestSuitedEdt.getText().toString();                String courseImg = courseImgEdt.getText().toString();                String courseLink = courseLinkEdt.getText().toString();                courseID = courseName;                // on below line we are passing all data to our modal class.                CourseRVModal courseRVModal = new CourseRVModal(courseID, courseName, courseDesc, coursePrice, bestSuited, courseImg, courseLink);                // on below line we are calling a add value event                // to pass data to firebase database.                databaseReference.addValueEventListener(new ValueEventListener() {                    @Override                    public void onDataChange(@NonNull DataSnapshot snapshot) {                        // on below line we are setting data in our firebase database.                        databaseReference.child(courseID).setValue(courseRVModal);                        // displaying a toast message.                        Toast.makeText(AddCourseActivity.this, "Course Added..", Toast.LENGTH_SHORT).show();                        // starting a main activity.                        startActivity(new Intent(AddCourseActivity.this, MainActivity.class));                    }                     @Override                    public void onCancelled(@NonNull DatabaseError error) {                        // displaying a failure message on below line.                        Toast.makeText(AddCourseActivity.this, "Fail to add Course..", Toast.LENGTH_SHORT).show();                    }                });            }        });    }}
 
Step 15: Creating an item for each course inside our Recycler View.
Navigate to app > res > Right-click on it > New Layout Resource file and name it as course_rv_item and add the below code to it. Comments are added in the code to get to know in more detail. 
XML
<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_gravity="center"    android:layout_margin="5dp"    app:cardCornerRadius="4dp"    app:cardElevation="3dp">     <RelativeLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="@color/black_shade_1">         <!--image view for our course-->        <ImageView            android:id="@+id/idIVCourse"            android:layout_width="match_parent"            android:layout_height="200dp"            android:scaleType="centerCrop" />         <!--text view for course name-->        <TextView            android:id="@+id/idTVCOurseName"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_below="@id/idIVCourse"            android:layout_margin="3dp"            android:layout_toStartOf="@id/idTVCousePrice"            android:layout_toLeftOf="@id/idTVCousePrice"            android:padding="4dp"            android:text="Course Name"            android:textColor="@color/white"            android:textSize="15sp"            android:textStyle="bold" />         <!--text view for course price-->        <TextView            android:id="@+id/idTVCousePrice"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_below="@id/idIVCourse"            android:layout_alignParentEnd="true"            android:layout_alignParentRight="true"            android:layout_margin="3dp"            android:gravity="center"            android:padding="4dp"            android:text="Price"            android:textColor="@color/white"            android:textSize="15sp"            android:textStyle="bold" />     </RelativeLayout> </androidx.cardview.widget.CardView>
 Step 16: Working with activity_main.xml file 
Navigate to the app > res > layout > activity_main.xml and add the below code to it. Comments are added in the code to get to know in more detail. 
XML
<?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:id="@+id/idRLHome"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@color/black_shade_1"    tools:context=".MainActivity">     <!--recycler view for our data-->    <androidx.recyclerview.widget.RecyclerView        android:id="@+id/idRVCourses"        android:layout_width="match_parent"        android:layout_height="wrap_content"        tools:listitem="@layout/course_rv_item" />     <!--progress bar for loading indicator-->    <ProgressBar        android:id="@+id/idPBLoading"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:indeterminate="true"        android:indeterminateDrawable="@drawable/progress_back" />     <!--floating action button-->    <com.google.android.material.floatingactionbutton.FloatingActionButton        android:id="@+id/idFABAddCourse"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentEnd="true"        android:layout_alignParentRight="true"        android:layout_alignParentBottom="true"        android:layout_margin="20dp"        android:src="@drawable/ic_add"        app:background="@color/black_shade_1"        app:backgroundTint="@color/black_shade_2"        app:tint="@color/white" /> </RelativeLayout>
 Step 17: Creating an Adapter class for setting data to each item of RecyclerView
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail. 
Java
package com.gtappdevelopers.firebasecrudapp; import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import android.widget.ImageView;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> {    // creating variables for our list, context, interface and position.    private ArrayList<CourseRVModal> courseRVModalArrayList;    private Context context;    private CourseClickInterface courseClickInterface;    int lastPos = -1;     // creating a constructor.    public CourseRVAdapter(ArrayList<CourseRVModal> courseRVModalArrayList, Context context, CourseClickInterface courseClickInterface) {        this.courseRVModalArrayList = courseRVModalArrayList;        this.context = context;        this.courseClickInterface = courseClickInterface;    }     @NonNull    @Override    public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {        // inflating our layout file on below line.        View view = LayoutInflater.from(context).inflate(R.layout.course_rv_item, parent, false);        return new ViewHolder(view);    }     @Override    public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {        // setting data to our recycler view item on below line.        CourseRVModal courseRVModal = courseRVModalArrayList.get(position);        holder.courseTV.setText(courseRVModal.getCourseName());        holder.coursePriceTV.setText("Rs. " + courseRVModal.getCoursePrice());        Picasso.get().load(courseRVModal.getCourseImg()).into(holder.courseIV);        // adding animation to recycler view item on below line.        setAnimation(holder.itemView, position);        holder.courseIV.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                courseClickInterface.onCourseClick(position);            }        });    }     private void setAnimation(View itemView, int position) {        if (position > lastPos) {            // on below line we are setting animation.            Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);            itemView.setAnimation(animation);            lastPos = position;        }    }     @Override    public int getItemCount() {        return courseRVModalArrayList.size();    }     public static class ViewHolder extends RecyclerView.ViewHolder {        // creating variable for our image view and text view on below line.        private ImageView courseIV;        private TextView courseTV, coursePriceTV;         public ViewHolder(@NonNull View itemView) {            super(itemView);            // initializing all our variables on below line.            courseIV = itemView.findViewById(R.id.idIVCourse);            courseTV = itemView.findViewById(R.id.idTVCOurseName);            coursePriceTV = itemView.findViewById(R.id.idTVCousePrice);        }    }     // creating a interface for on click    public interface CourseClickInterface {        void onCourseClick(int position);    }}
  Step 18: Creating a menu file for displaying menu options
Navigate to the app > res > Right-click on it > New > Directory and name it as menu. Now navigate to the menu directory, Right-click on it > New > Menu Resource file and name it as menu_main.xml and add the below code to it. Comments are added in the code to get to know in more detail. 
XML
<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android">    <!--specifying item for displaying option-->    <item        android:id="@+id/idLogOut"        android:icon="@drawable/ic_logout"        android:title="Log Out" /></menu>
  Step 19: Creating a layout file for displaying a bottom sheet 
Navigate to the app > res > layout > Right-click on it > New > Layout Resource file and name it as bottom_sheet_layout and add below code to it. Comments are added in the code to get to know in more detail. 
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/idRLBSheet"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="@color/black_shade_1"    android:padding="4dp">     <!--text view for displaying course name-->    <TextView        android:id="@+id/idTVCourseName"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="3dp"        android:padding="4dp"        android:text="Course Name"        android:textColor="@color/white"        android:textSize="15sp"        android:textStyle="bold" />     <!--image view for displaying course image-->    <ImageView        android:id="@+id/idIVCourse"        android:layout_width="100dp"        android:layout_height="100dp"        android:layout_below="@id/idTVCourseName"        android:layout_centerVertical="true"        android:layout_margin="4dp"        android:padding="4dp"        android:src="@drawable/ic_launcher_background" />     <!--text view for displaying course description-->    <TextView        android:id="@+id/idTVCourseDesc"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idTVCourseName"        android:layout_margin="4dp"        android:layout_toEndOf="@id/idIVCourse"        android:layout_toRightOf="@id/idIVCourse"        android:padding="3dp"        android:text="Description"        android:textColor="@color/white" />     <!--text view for displaying course best suited for-->    <TextView        android:id="@+id/idTVSuitedFor"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idTVCourseDesc"        android:layout_margin="4dp"        android:layout_toRightOf="@id/idIVCourse"        android:padding="3dp"        android:text="Suited for"        android:textColor="@color/white" />     <!--text view for displaying course price-->    <TextView        android:id="@+id/idTVCoursePrice"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idTVSuitedFor"        android:layout_margin="4dp"        android:layout_toRightOf="@id/idIVCourse"        android:padding="3dp"        android:text="Price"        android:textColor="@color/white"        android:textSize="18sp"        android:textStyle="bold" />      <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/idTVCoursePrice"        android:orientation="horizontal"        android:weightSum="2">         <!--button for editing course-->        <Button            android:id="@+id/idBtnEditCourse"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_margin="6dp"            android:layout_weight="1"            android:text="Edit Course"            android:textAllCaps="false" />         <!--button for viewing course details-->        <Button            android:id="@+id/idBtnVIewDetails"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_margin="6dp"            android:layout_weight="1"            android:text="View Details"            android:textAllCaps="false" />     </LinearLayout> </RelativeLayout>
 Step 20: Working with the MainActivity.java file 
Navigate to the app > java > your app’s package name > MainActivity.java file and add the below code to it. Comments are added in the code to get to know in detail. 
Java
package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.RelativeLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.bottomsheet.BottomSheetDialog;import com.google.android.material.floatingactionbutton.FloatingActionButton;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.database.ChildEventListener;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.squareup.picasso.Picasso; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements CourseRVAdapter.CourseClickInterface {     // creating variables for fab, firebase database,    // progress bar, list, adapter,firebase auth,    // recycler view and relative layout.    private FloatingActionButton addCourseFAB;    FirebaseDatabase firebaseDatabase;    DatabaseReference databaseReference;    private RecyclerView courseRV;    private FirebaseAuth mAuth;    private ProgressBar loadingPB;    private ArrayList<CourseRVModal> courseRVModalArrayList;    private CourseRVAdapter courseRVAdapter;    private RelativeLayout homeRL;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        // initializing all our variables.        courseRV = findViewById(R.id.idRVCourses);        homeRL = findViewById(R.id.idRLBSheet);        loadingPB = findViewById(R.id.idPBLoading);        addCourseFAB = findViewById(R.id.idFABAddCourse);        firebaseDatabase = FirebaseDatabase.getInstance();        mAuth = FirebaseAuth.getInstance();        courseRVModalArrayList = new ArrayList<>();        // on below line we are getting database reference.        databaseReference = firebaseDatabase.getReference("Courses");        // on below line adding a click listener for our floating action button.        addCourseFAB.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // opening a new activity for adding a course.                Intent i = new Intent(MainActivity.this, AddCourseActivity.class);                startActivity(i);            }        });        // on below line initializing our adapter class.        courseRVAdapter = new CourseRVAdapter(courseRVModalArrayList, this, this::onCourseClick);        // setting layout malinger to recycler view on below line.        courseRV.setLayoutManager(new LinearLayoutManager(this));        // setting adapter to recycler view on below line.        courseRV.setAdapter(courseRVAdapter);        // on below line calling a method to fetch courses from database.        getCourses();    }     private void getCourses() {        // on below line clearing our list.        courseRVModalArrayList.clear();        // on below line we are calling add child event listener method to read the data.        databaseReference.addChildEventListener(new ChildEventListener() {            @Override            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {                // on below line we are hiding our progress bar.                loadingPB.setVisibility(View.GONE);                // adding snapshot to our array list on below line.                courseRVModalArrayList.add(snapshot.getValue(CourseRVModal.class));                // notifying our adapter that data has changed.                courseRVAdapter.notifyDataSetChanged();            }             @Override            public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {                // this method is called when new child is added                // we are notifying our adapter and making progress bar                // visibility as gone.                loadingPB.setVisibility(View.GONE);                courseRVAdapter.notifyDataSetChanged();            }             @Override            public void onChildRemoved(@NonNull DataSnapshot snapshot) {                // notifying our adapter when child is removed.                courseRVAdapter.notifyDataSetChanged();                loadingPB.setVisibility(View.GONE);             }             @Override            public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {                // notifying our adapter when child is moved.                courseRVAdapter.notifyDataSetChanged();                loadingPB.setVisibility(View.GONE);            }             @Override            public void onCancelled(@NonNull DatabaseError error) {             }        });    }     @Override    public void onCourseClick(int position) {        // calling a method to display a bottom sheet on below line.        displayBottomSheet(courseRVModalArrayList.get(position));    }     @Override    public boolean onOptionsItemSelected(@NonNull MenuItem item) {        // adding a click listener for option selected on below line.        int id = item.getItemId();        switch (id) {            case R.id.idLogOut:                // displaying a toast message on user logged out inside on click.                Toast.makeText(getApplicationContext(), "User Logged Out", Toast.LENGTH_LONG).show();                // on below line we are signing out our user.                mAuth.signOut();                // on below line we are opening our login activity.                Intent i = new Intent(MainActivity.this, LoginActivity.class);                startActivity(i);                this.finish();                return true;            default:                return super.onOptionsItemSelected(item);        }    }     @Override    public boolean onCreateOptionsMenu(Menu menu) {        // on below line we are inflating our menu        // file for displaying our menu options.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }     private void displayBottomSheet(CourseRVModal modal) {        // on below line we are creating our bottom sheet dialog.        final BottomSheetDialog bottomSheetTeachersDialog = new BottomSheetDialog(this, R.style.BottomSheetDialogTheme);        // on below line we are inflating our layout file for our bottom sheet.        View layout = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_layout, homeRL);        // setting content view for bottom sheet on below line.        bottomSheetTeachersDialog.setContentView(layout);        // on below line we are setting a cancelable        bottomSheetTeachersDialog.setCancelable(false);        bottomSheetTeachersDialog.setCanceledOnTouchOutside(true);        // calling a method to display our bottom sheet.        bottomSheetTeachersDialog.show();        // on below line we are creating variables for        // our text view and image view inside bottom sheet        // and initialing them with their ids.        TextView courseNameTV = layout.findViewById(R.id.idTVCourseName);        TextView courseDescTV = layout.findViewById(R.id.idTVCourseDesc);        TextView suitedForTV = layout.findViewById(R.id.idTVSuitedFor);        TextView priceTV = layout.findViewById(R.id.idTVCoursePrice);        ImageView courseIV = layout.findViewById(R.id.idIVCourse);        // on below line we are setting data to different views on below line.        courseNameTV.setText(modal.getCourseName());        courseDescTV.setText(modal.getCourseDescription());        suitedForTV.setText("Suited for " + modal.getBestSuitedFor());        priceTV.setText("Rs." + modal.getCoursePrice());        Picasso.get().load(modal.getCourseImg()).into(courseIV);        Button viewBtn = layout.findViewById(R.id.idBtnVIewDetails);        Button editBtn = layout.findViewById(R.id.idBtnEditCourse);         // adding on click listener for our edit button.        editBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // on below line we are opening our EditCourseActivity on below line.                Intent i = new Intent(MainActivity.this, EditCourseActivity.class);                // on below line we are passing our course modal                i.putExtra("course", modal);                startActivity(i);            }        });        // adding click listener for our view button on below line.        viewBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // on below line we are navigating to browser                  // for displaying course details from its url                Intent i = new Intent(Intent.ACTION_VIEW);                i.setData(Uri.parse(modal.getCourseLink()));                startActivity(i);            }        });    }}
 
 Step 21: Working with activity_edit_course.xml file 
Navigate to the app > res > layout > activity_edit_course.xml and add the below code to it. Comments are added in the code to get to know in detail.
XML
<?xml version="1.0" encoding="utf-8"?><ScrollView    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:layout_height="match_parent"    android:background="@color/black_shade_1"    tools:context=".EditCourseActivity">     <RelativeLayout        android:layout_width="match_parent"        android:layout_height="wrap_content">         <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="vertical">             <!--edit text for adding a course name-->            <com.google.android.material.textfield.TextInputLayout                android:id="@+id/idTILCourseName"                style="@style/LoginTextInputLayoutStyle"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_marginLeft="10dp"                android:layout_marginTop="10dp"                android:layout_marginRight="10dp"                android:hint="Enter Course Name"                android:padding="5dp"                android:textColorHint="@color/white"                app:hintTextColor="@color/white">                 <com.google.android.material.textfield.TextInputEditText                    android:id="@+id/idEdtCourseName"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:ems="10"                    android:importantForAutofill="no"                    android:inputType="textImeMultiLine|textMultiLine"                    android:textColor="@color/white"                    android:textColorHint="@color/white"                    android:textSize="14sp" />            </com.google.android.material.textfield.TextInputLayout>             <!--edit text for adding a course price-->            <com.google.android.material.textfield.TextInputLayout                android:id="@+id/idTILCoursePrice"                style="@style/LoginTextInputLayoutStyle"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_marginLeft="10dp"                android:layout_marginTop="10dp"                android:layout_marginRight="10dp"                android:hint="Enter Course Price"                android:padding="5dp"                android:textColorHint="@color/white"                app:boxStrokeColor="@color/purple_200"                app:hintTextColor="@color/white">                 <com.google.android.material.textfield.TextInputEditText                    android:id="@+id/idEdtCoursePrice"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:ems="10"                    android:importantForAutofill="no"                    android:inputType="phone"                    android:textColor="@color/white"                    android:textColorHint="@color/white"                    android:textSize="14sp"                    app:boxStrokeColor="@color/purple_200" />            </com.google.android.material.textfield.TextInputLayout>             <!--edit text for adding a course best suited for-->            <com.google.android.material.textfield.TextInputLayout                android:id="@+id/idTILCourseSuitedFor"                style="@style/LoginTextInputLayoutStyle"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_marginLeft="10dp"                android:layout_marginTop="10dp"                android:layout_marginRight="10dp"                android:hint="Enter Course Suited For"                android:padding="5dp"                android:textColorHint="@color/white"                app:hintTextColor="@color/white">                 <com.google.android.material.textfield.TextInputEditText                    android:id="@+id/idEdtSuitedFor"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:ems="10"                    android:importantForAutofill="no"                    android:inputType="textImeMultiLine|textMultiLine"                    android:textColor="@color/white"                    android:textColorHint="@color/white"                    android:textSize="14sp" />            </com.google.android.material.textfield.TextInputLayout>             <!--edit text for adding a course image link-->            <com.google.android.material.textfield.TextInputLayout                android:id="@+id/idTILCourseImageLink"                style="@style/LoginTextInputLayoutStyle"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_marginLeft="10dp"                android:layout_marginTop="10dp"                android:layout_marginRight="10dp"                android:hint="Enter Course Image Link"                android:padding="5dp"                android:textColorHint="@color/white"                app:hintTextColor="@color/white">                 <com.google.android.material.textfield.TextInputEditText                    android:id="@+id/idEdtCourseImageLink"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:ems="10"                    android:importantForAutofill="no"                    android:inputType="textImeMultiLine|textMultiLine"                    android:textColor="@color/white"                    android:textColorHint="@color/white"                    android:textSize="14sp" />            </com.google.android.material.textfield.TextInputLayout>             <!--edit text for adding a course link-->            <com.google.android.material.textfield.TextInputLayout                android:id="@+id/idTILCourseLink"                style="@style/LoginTextInputLayoutStyle"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:layout_marginLeft="10dp"                android:layout_marginTop="10dp"                android:layout_marginRight="10dp"                android:hint="Enter Course Link"                android:padding="5dp"                android:textColorHint="@color/white"                app:hintTextColor="@color/white">                 <com.google.android.material.textfield.TextInputEditText                    android:id="@+id/idEdtCourseLink"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:ems="10"                    android:importantForAutofill="no"                    android:inputType="textImeMultiLine|textMultiLine"                    android:textColor="@color/white"                    android:textColorHint="@color/white"                    android:textSize="14sp" />            </com.google.android.material.textfield.TextInputLayout>              <!--edit text for adding a course description-->            <com.google.android.material.textfield.TextInputLayout                android:id="@+id/idTILCourseDescription"                style="@style/LoginTextInputLayoutStyle"                android:layout_width="match_parent"                android:layout_height="200dp"                android:layout_marginLeft="10dp"                android:layout_marginTop="10dp"                android:layout_marginRight="10dp"                android:hint="Enter Course Description"                android:padding="5dp"                android:textColorHint="@color/white"                app:hintTextColor="@color/white">                 <com.google.android.material.textfield.TextInputEditText                    android:id="@+id/idEdtCourseDescription"                    android:layout_width="match_parent"                    android:layout_height="match_parent"                    android:ems="10"                    android:importantForAutofill="no"                    android:inputType="textImeMultiLine|textMultiLine"                    android:textColor="@color/white"                    android:textColorHint="@color/white"                    android:textSize="14sp" />            </com.google.android.material.textfield.TextInputLayout>             <LinearLayout                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:orientation="horizontal"                android:weightSum="2">                 <!--button for updating a new course-->                <Button                    android:id="@+id/idBtnAddCourse"                    android:layout_width="0dp"                    android:layout_height="wrap_content"                    android:layout_marginStart="10dp"                    android:layout_marginTop="10dp"                    android:layout_marginEnd="10dp"                    android:layout_marginBottom="10dp"                    android:layout_weight="1"                    android:background="@drawable/button_back"                    android:text="Update Your \n Course"                    android:textAllCaps="false" />                 <!--button for deleting a course-->                <Button                    android:id="@+id/idBtnDeleteCourse"                    android:layout_width="0dp"                    android:layout_height="wrap_content"                    android:layout_marginStart="10dp"                    android:layout_marginTop="10dp"                    android:layout_marginEnd="10dp"                    android:layout_marginBottom="10dp"                    android:layout_weight="1"                    android:background="@drawable/button_back"                    android:text="Delete Your \n Course"                    android:textAllCaps="false" />             </LinearLayout>        </LinearLayout>         <!--progress bar for displaying a loading indicator-->        <ProgressBar            android:id="@+id/idPBLoading"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_centerInParent="true"            android:layout_gravity="center"            android:layout_marginTop="20dp"            android:indeterminate="true"            android:indeterminateDrawable="@drawable/progress_back"            android:visibility="gone" />     </RelativeLayout> </ScrollView>
 Step 22: Working with the EditCourseActivity.java file
Navigate to the app > java > your app’s package name > EditCourseActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. 
Java
package com.gtappdevelopers.firebasecrudapp; import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.textfield.TextInputEditText;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; import java.util.HashMap;import java.util.Map; public class EditCourseActivity extends AppCompatActivity {     // creating variables for our edit text, firebase database,    // database reference, course rv modal,progress bar.    private TextInputEditText courseNameEdt, courseDescEdt, coursePriceEdt, bestSuitedEdt, courseImgEdt, courseLinkEdt;    FirebaseDatabase firebaseDatabase;    DatabaseReference databaseReference;    CourseRVModal courseRVModal;    private ProgressBar loadingPB;    // creating a string for our course id.    private String courseID;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_edit_course);        // initializing all our variables on below line.        Button addCourseBtn = findViewById(R.id.idBtnAddCourse);        courseNameEdt = findViewById(R.id.idEdtCourseName);        courseDescEdt = findViewById(R.id.idEdtCourseDescription);        coursePriceEdt = findViewById(R.id.idEdtCoursePrice);        bestSuitedEdt = findViewById(R.id.idEdtSuitedFor);        courseImgEdt = findViewById(R.id.idEdtCourseImageLink);        courseLinkEdt = findViewById(R.id.idEdtCourseLink);        loadingPB = findViewById(R.id.idPBLoading);        firebaseDatabase = FirebaseDatabase.getInstance();        // on below line we are getting our modal class on which we have passed.        courseRVModal = getIntent().getParcelableExtra("course");        Button deleteCourseBtn = findViewById(R.id.idBtnDeleteCourse);         if (courseRVModal != null) {            // on below line we are setting data to our edit text from our modal class.            courseNameEdt.setText(courseRVModal.getCourseName());            coursePriceEdt.setText(courseRVModal.getCoursePrice());            bestSuitedEdt.setText(courseRVModal.getBestSuitedFor());            courseImgEdt.setText(courseRVModal.getCourseImg());            courseLinkEdt.setText(courseRVModal.getCourseLink());            courseDescEdt.setText(courseRVModal.getCourseDescription());            courseID = courseRVModal.getCourseId();        }         // on below line we are initialing our database reference and we are adding a child as our course id.        databaseReference = firebaseDatabase.getReference("Courses").child(courseID);        // on below line we are adding click listener for our add course button.        addCourseBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // on below line we are making our progress bar as visible.                loadingPB.setVisibility(View.VISIBLE);                // on below line we are getting data from our edit text.                String courseName = courseNameEdt.getText().toString();                String courseDesc = courseDescEdt.getText().toString();                String coursePrice = coursePriceEdt.getText().toString();                String bestSuited = bestSuitedEdt.getText().toString();                String courseImg = courseImgEdt.getText().toString();                String courseLink = courseLinkEdt.getText().toString();                // on below line we are creating a map for                // passing a data using key and value pair.                Map<String, Object> map = new HashMap<>();                map.put("courseName", courseName);                map.put("courseDescription", courseDesc);                map.put("coursePrice", coursePrice);                map.put("bestSuitedFor", bestSuited);                map.put("courseImg", courseImg);                map.put("courseLink", courseLink);                map.put("courseId", courseID);                 // on below line we are calling a database reference on                // add value event listener and on data change method                databaseReference.addValueEventListener(new ValueEventListener() {                    @Override                    public void onDataChange(@NonNull DataSnapshot snapshot) {                        // making progress bar visibility as gone.                        loadingPB.setVisibility(View.GONE);                        // adding a map to our database.                        databaseReference.updateChildren(map);                        // on below line we are displaying a toast message.                        Toast.makeText(EditCourseActivity.this, "Course Updated..", Toast.LENGTH_SHORT).show();                        // opening a new activity after updating our coarse.                        startActivity(new Intent(EditCourseActivity.this, MainActivity.class));                    }                     @Override                    public void onCancelled(@NonNull DatabaseError error) {                        // displaying a failure message on toast.                        Toast.makeText(EditCourseActivity.this, "Fail to update course..", Toast.LENGTH_SHORT).show();                    }                });            }        });         // adding a click listener for our delete course button.        deleteCourseBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // calling a method to delete a course.                deleteCourse();            }        });     }     private void deleteCourse() {        // on below line calling a method to delete the course.        databaseReference.removeValue();        // displaying a toast message on below line.        Toast.makeText(this, "Course Deleted..", Toast.LENGTH_SHORT).show();        // opening a main activity on below line.        startActivity(new Intent(EditCourseActivity.this, MainActivity.class));    }}
Note: All the drawable used inside the application are present in the app > res > drawable. You can check out the project on the below GitHub link.  
 Now run your app and see the output of the app. 
 Output:
ruhelaa48
surinderdawra388
varshagumber28
sweetyty
Android
Java
Project
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
For-each loop in Java