在上一篇文章中,我们了解了如何在Android的Firebase Firestore中添加数据,如何在Android的Firebase Firestore中读取数据。现在,我们将看到如何在Firebase Firestore中更新此添加的数据。现在,我们将着手在Android Firebase中实现此更新数据。
我们将在本文中构建什么?
我们将创建一个与添加数据时类似的屏幕,并在此屏幕中,在Firebase Firestore中更新数据,并且该数据也将在我们的应用程序中更新。
分步实施
步骤1:创建新的Activity以更新数据
要创建新的Activity,请导航至应用程序> res>布局>右键单击它,然后单击New>然后单击Empty Activity以创建一个新的Activity ,我们将其命名为UpdateCourse 。创建新的活动后,导航至应用程序> res>布局> activity_update_course.xml ,并将以下代码添加到其中。
XML
Java
import com.google.firebase.firestore.Exclude;
import java.io.Serializable;
// we have to implement our modal class
// with serializable so that we can pass
// our object class to new activity on
// our item click of recycler view.
public class Courses implements Serializable {
// getter method for our id
public String getId() {
return id;
}
// setter method for our id
public void setId(String id) {
this.id = id;
}
// we are using exclude because
// we are not saving our id
@Exclude
private String id;
// variables for storing our data.
private String courseName, courseDescription, courseDuration;
public Courses() {
// empty constructor required for Firebase.
}
// Constructor for all variables.
public Courses(String courseName, String courseDescription, String courseDuration) {
this.courseName = courseName;
this.courseDescription = courseDescription;
this.courseDuration = courseDuration;
}
// getter methods for all variables.
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseDescription() {
return courseDescription;
}
// setter method for all variables.
public void setCourseDescription(String courseDescription) {
this.courseDescription = courseDescription;
}
public String getCourseDuration() {
return courseDuration;
}
public void setCourseDuration(String courseDuration) {
this.courseDuration = courseDuration;
}
}
Java
// here we are adding on click listener
// for our item of recycler view.
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// after clicking of the item of recycler view.
// we are passing our course object to the new activity.
Courses courses = coursesArrayList.get(getAdapterPosition());
// below line is creating a new intent.
Intent i = new Intent(context, UpdateCourse.class);
// below line is for putting our course object to our next activity.
i.putExtra("course", courses);
// after passing the data we are starting our activity.
context.startActivity(i);
}
});
Java
import android.content.Context;
import android.content.Intent;
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 {
// creating variables for our ArrayList and context
private ArrayList coursesArrayList;
private Context context;
// creating constructor for our adapter class
public CourseRVAdapter(ArrayList coursesArrayList, Context context) {
this.coursesArrayList = coursesArrayList;
this.context = context;
}
@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_item, parent, false));
}
@Override
public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {
// setting data to our text views from our modal class.
Courses courses = coursesArrayList.get(position);
holder.courseNameTV.setText(courses.getCourseName());
holder.courseDurationTV.setText(courses.getCourseDuration());
holder.courseDescTV.setText(courses.getCourseDescription());
}
@Override
public int getItemCount() {
// returning the size of our array list.
return coursesArrayList.size();
}
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);
// here we are adding on click listener
// for our item of recycler view.
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// after clicking of the item of recycler view.
// we are passing our course object to the new activity.
Courses courses = coursesArrayList.get(getAdapterPosition());
// below line is creating a new intent.
Intent i = new Intent(context, UpdateCourse.class);
// below line is for putting our course object to our next activity.
i.putExtra("course", courses);
// after passing the data we are starting our activity.
context.startActivity(i);
}
});
}
}
}
Java
// below is the updated line of code which we have to
// add to pass the document id inside our modal class.
// we are setting our document id with d.getId() method
c.setId(d.getId());
Java
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class CourseDetails extends AppCompatActivity {
// creating variables for our recycler view,
// array list, adapter, firebase firestore
// and our progress bar.
private RecyclerView courseRV;
private ArrayList coursesArrayList;
private CourseRVAdapter courseRVAdapter;
private FirebaseFirestore db;
ProgressBar loadingPB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_details);
// initializing our variables.
courseRV = findViewById(R.id.idRVCourses);
loadingPB = findViewById(R.id.idProgressBar);
// initializing our variable for firebase
// firestore and getting its instance.
db = FirebaseFirestore.getInstance();
// creating our new array list
coursesArrayList = new ArrayList<>();
courseRV.setHasFixedSize(true);
courseRV.setLayoutManager(new LinearLayoutManager(this));
// adding our array list to our recycler view adapter class.
courseRVAdapter = new CourseRVAdapter(coursesArrayList, this);
// setting adapter to our recycler view.
courseRV.setAdapter(courseRVAdapter);
// below line is use to get the data from Firebase Firestore.
// previously we were saving data on a reference of Courses
// now we will be getting the data from the same reference.
db.collection("Courses").get()
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
// after getting the data we are calling on success method
// and inside this method we are checking if the received
// query snapshot is empty or not.
if (!queryDocumentSnapshots.isEmpty()) {
// if the snapshot is not empty we are
// hiding our progress bar and adding
// our data in a list.
loadingPB.setVisibility(View.GONE);
List list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
// after getting this list we are passing
// that list to our object class.
Courses c = d.toObject(Courses.class);
// below is the updated line of code which we have to
// add to pass the document id inside our modal class.
// we are setting our document id with d.getId() method
c.setId(d.getId());
// and we will pass this object class
// inside our arraylist which we have
// created for recycler view.
coursesArrayList.add(c);
}
// after adding the data to recycler view.
// we are calling recycler view notifuDataSetChanged
// method to notify that data has been changed in recycler view.
courseRVAdapter.notifyDataSetChanged();
} else {
// if the snapshot is empty we are displaying a toast message.
Toast.makeText(CourseDetails.this, "No data found in Database", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// if we do not get any data or any error we are displaying
// a toast message that we do not get any data
Toast.makeText(CourseDetails.this, "Fail to get the data.", Toast.LENGTH_SHORT).show();
}
});
}
}
Java
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.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.FirebaseFirestore;
public class UpdateCourse extends AppCompatActivity {
// creating variables for our edit text
private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
// creating a strings for storing our values from Edittext fields.
private String courseName, courseDuration, courseDescription;
// creating a variable for firebasefirestore.
private FirebaseFirestore db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_course);
Courses courses = (Courses) getIntent().getSerializableExtra("course");
// getting our instance from Firebase Firestore.
db = FirebaseFirestore.getInstance();
// initializing our edittext and buttons
courseNameEdt = findViewById(R.id.idEdtCourseName);
courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
// creating variable for button
Button updateCOurseBtn = findViewById(R.id.idBtnUpdateCourse);
courseNameEdt.setText(courses.getCourseName());
courseDescriptionEdt.setText(courses.getCourseDescription());
courseDurationEdt.setText(courses.getCourseDuration());
updateCOurseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
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 a method to update our course.
// we are passing our object class, course name,
// course description and course duration from our edittext field.
updateCourses(courses, courseName, courseDescription, courseDuration);
}
}
});
}
private void updateCourses(Courses courses, String courseName, String courseDescription, String courseDuration) {
// inside this method we are passing our updated values
// inside our object class and later on we
// will pass our whole object to firebase Firestore.
Courses updatedCourse = new Courses(courseName, courseDescription, courseDuration);
// after passing data to object class we are
// sending it to firebase with specific document id.
// below line is use to get the collection of our Firebase Firestore.
db.collection("Courses").
// below line is use toset the id of
// document where we have to perform
// update operation.
document(courses.getId()).
// after setting our document id we are
// passing our whole object class to it.
set(updatedCourse).
// after passing our object class we are
// calling a method for on success listener.
addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
// on successful completion of this process
// we are displaying the toast message.
Toast.makeText(UpdateCourse.this, "Course has been updated..", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
// inside on failure method we are
// displaying a failure message.
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(UpdateCourse.this, "Fail to update the data..", Toast.LENGTH_SHORT).show();
}
});
}
}
第2步:更新存储数据的模态类
在以前的文章中,我们已经看到了创建Modal类。在本文中,我们将更新Modal类,以便可以将对象类从适配器传递到活动中进行导航。除了可序列化的实现之外,我们还必须创建一个新的字符串变量,并为该变量创建一个getter和setter方法。我们将使用该变量存储文档的ID。以下是更新后的课程的代码。 Java类。在代码内部添加了注释,以便更详细地了解。
Java
import com.google.firebase.firestore.Exclude;
import java.io.Serializable;
// we have to implement our modal class
// with serializable so that we can pass
// our object class to new activity on
// our item click of recycler view.
public class Courses implements Serializable {
// getter method for our id
public String getId() {
return id;
}
// setter method for our id
public void setId(String id) {
this.id = id;
}
// we are using exclude because
// we are not saving our id
@Exclude
private String id;
// variables for storing our data.
private String courseName, courseDescription, courseDuration;
public Courses() {
// empty constructor required for Firebase.
}
// Constructor for all variables.
public Courses(String courseName, String courseDescription, String courseDuration) {
this.courseName = courseName;
this.courseDescription = courseDescription;
this.courseDuration = courseDuration;
}
// getter methods for all variables.
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseDescription() {
return courseDescription;
}
// setter method for all variables.
public void setCourseDescription(String courseDescription) {
this.courseDescription = courseDescription;
}
public String getCourseDuration() {
return courseDuration;
}
public void setCourseDuration(String courseDuration) {
this.courseDuration = courseDuration;
}
}
步骤3:为我们的RecyclerView项目添加onClickListener()
正如我们在上一篇文章中创建了Adapter类之后,该类用于在Recycler View中显示课程列表。在本文中,我们将在该Adapter类内为RecyclerView项目单击侦听器添加onClickListener() 。将以下代码段添加到CourseRVAdapter。 Java文件。
Java
// here we are adding on click listener
// for our item of recycler view.
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// after clicking of the item of recycler view.
// we are passing our course object to the new activity.
Courses courses = coursesArrayList.get(getAdapterPosition());
// below line is creating a new intent.
Intent i = new Intent(context, UpdateCourse.class);
// below line is for putting our course object to our next activity.
i.putExtra("course", courses);
// after passing the data we are starting our activity.
context.startActivity(i);
}
});
下面是CourseRVAdapter的更新代码。 Java文件。
Java
import android.content.Context;
import android.content.Intent;
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 {
// creating variables for our ArrayList and context
private ArrayList coursesArrayList;
private Context context;
// creating constructor for our adapter class
public CourseRVAdapter(ArrayList coursesArrayList, Context context) {
this.coursesArrayList = coursesArrayList;
this.context = context;
}
@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_item, parent, false));
}
@Override
public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {
// setting data to our text views from our modal class.
Courses courses = coursesArrayList.get(position);
holder.courseNameTV.setText(courses.getCourseName());
holder.courseDurationTV.setText(courses.getCourseDuration());
holder.courseDescTV.setText(courses.getCourseDescription());
}
@Override
public int getItemCount() {
// returning the size of our array list.
return coursesArrayList.size();
}
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);
// here we are adding on click listener
// for our item of recycler view.
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// after clicking of the item of recycler view.
// we are passing our course object to the new activity.
Courses courses = coursesArrayList.get(getAdapterPosition());
// below line is creating a new intent.
Intent i = new Intent(context, UpdateCourse.class);
// below line is for putting our course object to our next activity.
i.putExtra("course", courses);
// after passing the data we are starting our activity.
context.startActivity(i);
}
});
}
}
}
步骤4:更新CourseDetails中的代码。 Java文件
由于我们在模态类中创建了一个用于存储文档ID的新变量,因此我们必须初始化该变量并将文档ID传递到该变量中。为了传递该文档ID,我们必须更新CourseDetails的代码。显示我们已添加的所有课程列表的Java文件。将以下代码段添加到CourseRVAdapter。 Java文件。
Java
// below is the updated line of code which we have to
// add to pass the document id inside our modal class.
// we are setting our document id with d.getId() method
c.setId(d.getId());
以下是CourseDetails的更新代码。 Java文件。
Java
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class CourseDetails extends AppCompatActivity {
// creating variables for our recycler view,
// array list, adapter, firebase firestore
// and our progress bar.
private RecyclerView courseRV;
private ArrayList coursesArrayList;
private CourseRVAdapter courseRVAdapter;
private FirebaseFirestore db;
ProgressBar loadingPB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_details);
// initializing our variables.
courseRV = findViewById(R.id.idRVCourses);
loadingPB = findViewById(R.id.idProgressBar);
// initializing our variable for firebase
// firestore and getting its instance.
db = FirebaseFirestore.getInstance();
// creating our new array list
coursesArrayList = new ArrayList<>();
courseRV.setHasFixedSize(true);
courseRV.setLayoutManager(new LinearLayoutManager(this));
// adding our array list to our recycler view adapter class.
courseRVAdapter = new CourseRVAdapter(coursesArrayList, this);
// setting adapter to our recycler view.
courseRV.setAdapter(courseRVAdapter);
// below line is use to get the data from Firebase Firestore.
// previously we were saving data on a reference of Courses
// now we will be getting the data from the same reference.
db.collection("Courses").get()
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
// after getting the data we are calling on success method
// and inside this method we are checking if the received
// query snapshot is empty or not.
if (!queryDocumentSnapshots.isEmpty()) {
// if the snapshot is not empty we are
// hiding our progress bar and adding
// our data in a list.
loadingPB.setVisibility(View.GONE);
List list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
// after getting this list we are passing
// that list to our object class.
Courses c = d.toObject(Courses.class);
// below is the updated line of code which we have to
// add to pass the document id inside our modal class.
// we are setting our document id with d.getId() method
c.setId(d.getId());
// and we will pass this object class
// inside our arraylist which we have
// created for recycler view.
coursesArrayList.add(c);
}
// after adding the data to recycler view.
// we are calling recycler view notifuDataSetChanged
// method to notify that data has been changed in recycler view.
courseRVAdapter.notifyDataSetChanged();
} else {
// if the snapshot is empty we are displaying a toast message.
Toast.makeText(CourseDetails.this, "No data found in Database", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// if we do not get any data or any error we are displaying
// a toast message that we do not get any data
Toast.makeText(CourseDetails.this, "Fail to get the data.", Toast.LENGTH_SHORT).show();
}
});
}
}
步骤5:现在,我们将着手实施UpdateCourses。 Java文件
更新我们的适配器类后,导航至应用程序> Java >您的应用程序的程序包名称> UpdateCourses。 Java文件,并向其中添加以下代码。在代码内部添加了注释,以更详细地了解代码。
Java
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.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.FirebaseFirestore;
public class UpdateCourse extends AppCompatActivity {
// creating variables for our edit text
private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
// creating a strings for storing our values from Edittext fields.
private String courseName, courseDuration, courseDescription;
// creating a variable for firebasefirestore.
private FirebaseFirestore db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_course);
Courses courses = (Courses) getIntent().getSerializableExtra("course");
// getting our instance from Firebase Firestore.
db = FirebaseFirestore.getInstance();
// initializing our edittext and buttons
courseNameEdt = findViewById(R.id.idEdtCourseName);
courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
// creating variable for button
Button updateCOurseBtn = findViewById(R.id.idBtnUpdateCourse);
courseNameEdt.setText(courses.getCourseName());
courseDescriptionEdt.setText(courses.getCourseDescription());
courseDurationEdt.setText(courses.getCourseDuration());
updateCOurseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
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 a method to update our course.
// we are passing our object class, course name,
// course description and course duration from our edittext field.
updateCourses(courses, courseName, courseDescription, courseDuration);
}
}
});
}
private void updateCourses(Courses courses, String courseName, String courseDescription, String courseDuration) {
// inside this method we are passing our updated values
// inside our object class and later on we
// will pass our whole object to firebase Firestore.
Courses updatedCourse = new Courses(courseName, courseDescription, courseDuration);
// after passing data to object class we are
// sending it to firebase with specific document id.
// below line is use to get the collection of our Firebase Firestore.
db.collection("Courses").
// below line is use toset the id of
// document where we have to perform
// update operation.
document(courses.getId()).
// after setting our document id we are
// passing our whole object class to it.
set(updatedCourse).
// after passing our object class we are
// calling a method for on success listener.
addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
// on successful completion of this process
// we are displaying the toast message.
Toast.makeText(UpdateCourse.this, "Course has been updated..", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
// inside on failure method we are
// displaying a failure message.
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(UpdateCourse.this, "Fail to update the data..", Toast.LENGTH_SHORT).show();
}
});
}
}