我们已经看到了将数据添加到Android应用程序中的Back4App数据库中。在本文中,我们将看一下从Android应用程序中的数据库中读取此数据的方法。
我们将在本文中构建什么?
我们将在先前的应用程序中创建一个新屏幕,在该屏幕中,我们将显示在RecyclerView中添加到Back4App数据库中的数据。
分步实施
步骤1:使用activity_main.xml文件
转到activity_main.xml文件,再添加一个按钮,以显示所有已添加课程的列表。下面是代码片段,最后添加了代码。
XML
XML
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;
}
}
XML
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 {
private Context context;
private ArrayList courseModalArrayList;
// creating a constructor class.
public CourseRVAdapter(Context context, ArrayList 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);
}
}
}
XML
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 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 query = ParseQuery.getQuery("courses");
query.findInBackground(new FindCallback() {
@Override
public void done(List 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 ot 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);
}
}
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);
}
});
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();
}
}
});
}
}
现在下面是activity_main.xml文件的更新代码 添加以上代码段后。
XML格式
第2步:现在,我们将创建新的Activity,以在RecyclerView中显示Firebase Firestore中的数据
要创建一个新的活动,我们必须导航到应用程序> Java >您的应用程序的包名称>右键单击包名称>新建>空活动,并将您的活动命名为HomeActivity并创建新的活动。确保选择空白活动。
第3步:创建用于存储数据的模式类。
导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为CourseModal,然后将以下代码添加到其中。在代码中添加了注释,以便更详细地了解。
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;
}
}
步骤4:现在,我们将为RecyclerView项目创建一个卡片布局
要为RecyclerView创建新项目,请导航至应用程序> res>布局>右键单击layout>新建>布局资源文件,并将其命名为course_rv_item.xml,然后在其中添加以下代码。
XML格式
步骤5:现在我们将创建Adapter类,该类将处理RecyclerView项的数据
要为我们的Recycler View创建Adapter类,请导航至应用程序> Java >您的应用程序包名称>右键单击它,然后单击>新建> Java类,并将您的类命名为CourseRVAdapter 。创建这些类后,将以下代码添加到其中。在代码中添加了注释,以更详细地了解。
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 {
private Context context;
private ArrayList courseModalArrayList;
// creating a constructor class.
public CourseRVAdapter(Context context, ArrayList 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);
}
}
}
步骤6:使用activity_home.xml文件
导航至应用程序> res>布局> activity_home.xml文件,然后将以下代码添加到其中。
XML格式
步骤7:使用HomeActivity。 Java文件
导航到应用程序> Java >应用程序的程序包名称> HomeActivity。 Java文件,并向其中添加以下代码。
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 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 query = ParseQuery.getQuery("courses");
query.findInBackground(new FindCallback() {
@Override
public void done(List 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 ot 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);
}
}
步骤8:使用MainActivity。 Java文件
在MainActivity中。 Java文件,我们必须向HomeActivity文件添加一个Intent 。下面是执行此操作的代码段。
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);
}
});
以下是MainActivity的更新代码。 Java文件。
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();
}
}
});
}
}
现在运行您的应用程序,并查看该应用程序的输出。
输出:
以下是执行读取操作后Android Studio中的文件结构: