Open In App

How to Read Data from Back4App Database in Android?

Last Updated : 05 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

We have seen adding data to the Back4App database in the Android app. In this article, we will take a look at reading this data from our database in our Android App.

What we are going to build in this article? 

We will be creating a new screen in the previous application and inside that, we will display our data which we added inside our Back4App Database in the RecyclerView.

Step by Step Implementation

Step 1: Working with the activity_main.xml file

Go to the activity_main.xml file add one more Button for showing the list of all added courses. Below is the code snippet and add the code at last. 

XML




<!--Button for reading your course to Firebase-->
<Button
  android:id="@+id/idBtnReadCourse"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_margin="10dp"
  android:text="Read Course Details"
  android:textAllCaps="false" />


Now below is the updated code for the activity_main.xml file after adding the above code snippet.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--Edit text for getting course Name-->
    <EditText
        android:id="@+id/idEdtCourseName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="10dp"
        android:hint="Course Name"
        android:importantForAutofill="no"
        android:inputType="text" />
 
    <!--Edittext for getting course Duration-->
    <EditText
        android:id="@+id/idEdtCourseDuration"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="10dp"
        android:hint="Course Duration in min"
        android:importantForAutofill="no"
        android:inputType="time" />
 
    <!--Edittext for getting course Description-->
    <EditText
        android:id="@+id/idEdtCourseDescription"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="10dp"
        android:hint="Course Description"
        android:importantForAutofill="no"
        android:inputType="text" />
 
    <!--Button for adding your course to Firebase-->
    <Button
        android:id="@+id/idBtnSubmitCourse"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Submit Course Details"
        android:textAllCaps="false" />
 
    <!--Button for reading your course to Firebase-->
    <Button
        android:id="@+id/idBtnReadCourse"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Read Course Details"
        android:textAllCaps="false" />
 
</LinearLayout>


Step 2: Now we will create new Activity for displaying our data from Firebase Firestore in RecyclerView

To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as HomeActivity and create new Activity. Make sure to select the empty activity. 

Step 3: Creating a modal class for storing our data. 

Navigate to the app > java > your app’s package name > Right-click on it > New > java class and name it as CourseModal and add the below code to it. Comments are added in the code to get to know in more detail. 

Java




public class CourseModal {
 
    // variables for our course name,
    // description and duration.
    private String courseName;
    private String courseDescription;
    private String courseDuration;
 
    // constructor class.
    public CourseModal(String courseName, String courseDescription, String courseDuration) {
        this.courseName = courseName;
        this.courseDescription = courseDescription;
        this.courseDuration = courseDuration;
    }
 
    // 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 getCourseDuration() {
        return courseDuration;
    }
 
    public void setCourseDuration(String courseDuration) {
        this.courseDuration = courseDuration;
    }
}


Step 4: Now we will create a card layout for our item of RecyclerView

To create a new item for RecyclerView, navigate to the app > res > layout > Right-click on layout > New > layout resource file and name as course_rv_item.xml and add below code to it. 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    android:id="@+id/idCVCOurseItem"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    app:cardCornerRadius="6dp"
    app:cardElevation="4dp">
     
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"
        android:orientation="vertical"
        android:padding="4dp">
 
        <!--Textview for displaying our Course Name-->
        <TextView
            android:id="@+id/idTVCourseName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="2dp"
            android:text="CourseName"
            android:textColor="@color/purple_500"
            android:textSize="18sp"
            android:textStyle="bold" />
         
        <!--Textview for displaying our Course Duration-->
        <TextView
            android:id="@+id/idTVCourseDuration"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="2dp"
            android:text="Duration"
            android:textColor="@color/black" />
         
        <!--Textview for displaying our Course Description-->
        <TextView
            android:id="@+id/idTVCourseDescription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="2dp"
            android:text="Description"
            android:textColor="@color/black" />
         
    </LinearLayout>
     
</androidx.cardview.widget.CardView>


Step 5: Now we will create our Adapter class which will handle data for our RecyclerView items

For creating an Adapter class for our Recycler View, navigate to the app > java > Your app’s package name > Right-click on it and Click > New > Java class and name your class as CourseRVAdapter. After creating these class add the below code to it. Comments are added in the code to know in more detail. 

Java




import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
 
import java.util.ArrayList;
 
public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> {
    private Context context;
    private ArrayList<CourseModal> courseModalArrayList;
 
    // creating a constructor class.
    public CourseRVAdapter(Context context, ArrayList<CourseModal> courseModalArrayList) {
        this.context = context;
        this.courseModalArrayList = courseModalArrayList;
    }
 
    @NonNull
    @Override
    public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // passing our layout file for displaying our card item
        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_rv_item, parent, false));
    }
 
    @Override
    public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {
        // setting data to our text views from our modal class.
        CourseModal courses = courseModalArrayList.get(position);
        holder.courseNameTV.setText(courses.getCourseName());
        holder.courseDurationTV.setText(courses.getCourseDuration());
        holder.courseDescTV.setText(courses.getCourseDescription());
    }
 
    @Override
    public int getItemCount() {
        return courseModalArrayList.size();
    }
 
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our text views.
        private final TextView courseNameTV;
        private final TextView courseDurationTV;
        private final TextView courseDescTV;
 
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our text views.
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);
            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
        }
    }
}


Step 6: Working with the activity_home.xml file

Navigate to the app > res > layout > activity_home.xml file and add the below code to it. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HomeActivity">
 
    <!--Recycler view for displaying our data from Firestore-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVCourses"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
    <!--Progress bar for showing loading screen-->
    <ProgressBar
        android:id="@+id/idProgressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
 
</RelativeLayout>


Step 7: Working with the HomeActivity.java file 

Navigate to app > java > your app’s package name > HomeActivity.java file and add the below code to it. 

Java




import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
 
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
 
import java.util.ArrayList;
import java.util.List;
 
public class HomeActivity extends AppCompatActivity {
     
    // creating variables for our recycler view,
    // progressbar, array list and adapter class.
    private RecyclerView coursesRV;
    private ProgressBar loadingPB;
    private ArrayList<CourseModal> courseModalArrayList;
    private CourseRVAdapter courseRVAdapter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
         
        // initializing our views.
        loadingPB = findViewById(R.id.idProgressBar);
        coursesRV = findViewById(R.id.idRVCourses);
        courseModalArrayList = new ArrayList<>();
         
        // calling a method to
        // load recycler view.
        prepareCourseRV();
        
        // calling a method to get
        // the data from database.
        getDataFromServer();
    }
 
    private void getDataFromServer() {
        // Configure Query with our query.
        ParseQuery<ParseObject> query = ParseQuery.getQuery("courses");
        query.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> objects, ParseException e) {
                // in done method checking if the error is null or not.
                if (e == null) {
                    // Adding objects into the Array
                    // if error is not null we are getting data from
                    // our object and passing it to our array list.
                    for (int i = 0; i < objects.size(); i++) {
                         
                        // on below line we are extracting our
                        // data and adding it to our array list
                        String courseName = objects.get(i).getString("courseName");
                        String courseDescription = objects.get(i).getString("courseDescription");
                        String courseDuration = objects.get(i).getString("courseDuration");
                         
                        // on below line we are adding data to our array list.
                        courseModalArrayList.add(new CourseModal(courseName, courseDescription, courseDuration));
                    }
                    // notifying adapter class on adding new data.
                    courseRVAdapter.notifyDataSetChanged();
                    loadingPB.setVisibility(View.GONE);
                } else {
                    // handling error if we get any error.
                    Toast.makeText(HomeActivity.this, "Fail to get data..", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
 
    private void prepareCourseRV() {
         
        coursesRV.setHasFixedSize(true);
        coursesRV.setLayoutManager(new LinearLayoutManager(this));
         
        // adding our array list to our recycler view adapter class.
        courseRVAdapter = new CourseRVAdapter(this, courseModalArrayList);
         
        // setting adapter to our recycler view.
        coursesRV.setAdapter(courseRVAdapter);
    }
}


Step 8: Working with the MainActivity.java file

In the MainActivity.java file, we have to add an Intent to the HomeActivity file. Below is the code snippet to do so.

Java




readCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // opening new intent to read our data.
                Intent i = new Intent(MainActivity.this, HomeActivity.class);
                startActivity(i);
       }
});


Below is the updated code for the MainActivity.java file.

Java




import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
 
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.SaveCallback;
 
public class MainActivity extends AppCompatActivity {
 
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
 
    // creating variable for button
    private Button submitCourseBtn, readCourseBtn;
 
    // creating a strings for storing our values from edittext fields.
    private String courseName, courseDuration, courseDescription;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // initializing our edittext and buttons
        readCourseBtn = findViewById(R.id.idBtnReadCourse);
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
        submitCourseBtn = findViewById(R.id.idBtnSubmitCourse);
 
        readCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // opening new intent to read our data.
                Intent i = new Intent(MainActivity.this, HomeActivity.class);
                startActivity(i);
            }
        });
 
        submitCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
                // getting data from edittext fields.
                courseName = courseNameEdt.getText().toString();
                courseDescription = courseDescriptionEdt.getText().toString();
                courseDuration = courseDurationEdt.getText().toString();
 
                // validating the text fields if empty or not.
                if (TextUtils.isEmpty(courseName)) {
                    courseNameEdt.setError("Please enter Course Name");
                } else if (TextUtils.isEmpty(courseDescription)) {
                    courseDescriptionEdt.setError("Please enter Course Description");
                } else if (TextUtils.isEmpty(courseDuration)) {
                    courseDurationEdt.setError("Please enter Course Duration");
                } else {
                    // calling method to add data to Firebase Firestore.
                    addDataToDatabase(courseName, courseDescription, courseDuration);
                }
            }
        });
    }
 
    private void addDataToDatabase(String courseName, String courseDescription, String courseDuration) {
 
        // Configure Query
        ParseObject courseList = new ParseObject("courses");
 
        // on below line we are adding our data with their key value in our object.
        courseList.put("courseName", courseName);
        courseList.put("courseDescription", courseDescription);
        courseList.put("courseDuration", courseDuration);
 
        // after adding all data we are calling a
        // method to save our data in background.
        courseList.saveInBackground(new SaveCallback() {
            @Override
            public void done(ParseException e) {
                // inside on done method we are checking
                // if the error is null or not.
                if (e == null) {
 
                    // if the error is null we are displaying a simple toast message.
                    Toast.makeText(MainActivity.this, "Data has been successfully added to Database", Toast.LENGTH_SHORT).show();
 
                    // on below line we are setting our edit text fields to empty value.
                    courseNameEdt.setText("");
                    courseDescriptionEdt.setText("");
                    courseDurationEdt.setText("");
                } else {
                    // if the error is not null we will be
                    // displaying an error message to our user.
                    Toast.makeText(getApplicationContext(), e.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}


Now run your app and see the output of the app. 

Output:

Below is the file structure in Android Studio after performing the Read operation:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads