📌  相关文章
📜  如何在Android的Back4App数据库中更新数据?

📅  最后修改于: 2021-05-13 18:12:58             🧑  作者: Mango

在上一篇文章中,我们已经看到在Android应用程序中的Bac4App数据库中添加数据以及从中读取数据。在本文中,我们将介绍更新数据库中的数据

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在其中将更新Back4App数据库中以前添加的数据。

分步实施

步骤1:创建新的Activity以更新数据

要创建新的Activity,请导航至应用程序> res>布局>右键单击它,然后单击New>然后单击Empty Activity以创建新的Activity,我们将其命名为UpdateCourseActivity

步骤2:更新我们的Adapter类,以在单击RecyclerView项时打开一个新活动

正如我们在上一篇文章中创建了Adapter类之后,该类用于在Recycler View中显示课程列表。在本文中,我们将在该Adapter类内为RecyclerView项目单击侦听器添加onClickListener() 。将以下代码段添加到CourseRVAdapter。 Java文件。

Java
// adding on click listner for our item of recycler view.
holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
                // calling a intent to open new activity.
                Intent i = new Intent(context, UpdateCourseActivity.class);
                 
                // on below line we are passing data to our intent on below line.
                i.putExtra("courseName", courses.getCourseName());
                i.putExtra("courseDescription", courses.getCourseDescription());
                i.putExtra("courseDuration", courses.getCourseDuration());
                 
                // starting our activity on below line.
                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 {
    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());
 
        // adding on click listner for our item of recycler view.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 
                // calling a intent to open new activity.
                Intent i = new Intent(context, UpdateCourseActivity.class);
                 
                // on below line we are passing data to our intent on below line.
                i.putExtra("courseName", courses.getCourseName());
                i.putExtra("courseDescription", courses.getCourseDescription());
                i.putExtra("courseDuration", courses.getCourseDuration());
                 
                // starting our activity on below line.
                context.startActivity(i);
            }
        });
    }
 
    @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.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.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
 
public class UpdateCourseActivity extends AppCompatActivity {
 
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
     
    // creating variable for button
    private Button updateCourseBtn;
     
    // creating a strings for storing our values from edittext fields.
    private String courseName, courseDuration, courseDescription, originalCourseName, objectID;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_course);
         
        // initializing our edittext and buttons
        updateCourseBtn = findViewById(R.id.idBtnUpdate);
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
         
        // on below line we are setting data to our edit text field.
        courseNameEdt.setText(getIntent().getStringExtra("courseName"));
        courseDescriptionEdt.setText(getIntent().getStringExtra("courseDescription"));
        courseDurationEdt.setText(getIntent().getStringExtra("courseDuration"));
        originalCourseName = getIntent().getStringExtra("courseName");
        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 method to update data.
                    updateData(originalCourseName, courseName, courseDescription, courseDuration);
                }
            }
        });
    }
 
    private void updateData(String originalCourseName, String courseName, String courseDescription, String courseDuration) {
         
        // Configure Query with our query.
        ParseQuery query = ParseQuery.getQuery("courses");
         
        // adding a condition where our course name must be equal to the original course name
        query.whereEqualTo("courseName", originalCourseName);
         
        // in below method we are getting the unique id
        // of the course which we have to make update.
        query.getFirstInBackground(new GetCallback() {
            @Override
            public void done(ParseObject object, ParseException e) {
                // inside done method we check
                // if the error is null or not.
                if (e == null) {
                     
                    // if the error is null then we are getting
                    // our object id in below line.
                    objectID = object.getObjectId().toString();
                     
                    // after getting our object id we will
                    // move towards updating our course.
                    // calling below method to update our course.
                    query.getInBackground(objectID, new GetCallback() {
                        @Override
                        public void done(ParseObject object, ParseException e) {
                            // in this method we are getting the
                            // object which we have to update.
                            if (e == null) {
                                 
                                // in below line we are adding new data
                                // to the object which we get from its id.
                                // on below line we are adding our data
                                // with their key value in our object.
                                object.put("courseName", courseName);
                                object.put("courseDescription", courseDescription);
                                object.put("courseDuration", courseDuration);
                                 
                                // after adding new data then we are
                                // calling a method to save this data
                                object.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 our data has been updated.
                                            // we are displaying a toast message and redirecting
                                            // our user to home activity where we are displaying course list.
                                            Toast.makeText(UpdateCourseActivity.this, "Course Updated..", Toast.LENGTH_SHORT).show();
                                            Intent i = new Intent(UpdateCourseActivity.this, HomeActivity.class);
                                            startActivity(i);
                                        } else {
                                            // below line is for error handling.
                                            Toast.makeText(UpdateCourseActivity.this, "Fail to update data " + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            } else {
                                // on below line we are displaying a message
                                // if we don't get the object from its id.
                                Toast.makeText(UpdateCourseActivity.this, "Fail to update course " + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } else {
                    // this is error handling if we don't get the id for our object
                    Toast.makeText(UpdateCourseActivity.this, "Fail to get object ID..", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}


下面是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 {
    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());
 
        // adding on click listner for our item of recycler view.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 
                // calling a intent to open new activity.
                Intent i = new Intent(context, UpdateCourseActivity.class);
                 
                // on below line we are passing data to our intent on below line.
                i.putExtra("courseName", courses.getCourseName());
                i.putExtra("courseDescription", courses.getCourseDescription());
                i.putExtra("courseDuration", courses.getCourseDuration());
                 
                // starting our activity on below line.
                context.startActivity(i);
            }
        });
    }
 
    @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);
        }
    }
}

步骤3:使用activity_update_course.xml文件

导航到应用程序> res>布局> activity_update_course.xml,然后将以下代码添加到其中。

XML格式



 
    
    
 
    
    
 
    
    
 
    
 
        
        

步骤4:使用UpdateCourseActivity。 Java文件

导航到应用程序> Java >您的应用程序包名称> UpdateCourseActivity。 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.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
 
public class UpdateCourseActivity extends AppCompatActivity {
 
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
     
    // creating variable for button
    private Button updateCourseBtn;
     
    // creating a strings for storing our values from edittext fields.
    private String courseName, courseDuration, courseDescription, originalCourseName, objectID;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_course);
         
        // initializing our edittext and buttons
        updateCourseBtn = findViewById(R.id.idBtnUpdate);
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
         
        // on below line we are setting data to our edit text field.
        courseNameEdt.setText(getIntent().getStringExtra("courseName"));
        courseDescriptionEdt.setText(getIntent().getStringExtra("courseDescription"));
        courseDurationEdt.setText(getIntent().getStringExtra("courseDuration"));
        originalCourseName = getIntent().getStringExtra("courseName");
        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 method to update data.
                    updateData(originalCourseName, courseName, courseDescription, courseDuration);
                }
            }
        });
    }
 
    private void updateData(String originalCourseName, String courseName, String courseDescription, String courseDuration) {
         
        // Configure Query with our query.
        ParseQuery query = ParseQuery.getQuery("courses");
         
        // adding a condition where our course name must be equal to the original course name
        query.whereEqualTo("courseName", originalCourseName);
         
        // in below method we are getting the unique id
        // of the course which we have to make update.
        query.getFirstInBackground(new GetCallback() {
            @Override
            public void done(ParseObject object, ParseException e) {
                // inside done method we check
                // if the error is null or not.
                if (e == null) {
                     
                    // if the error is null then we are getting
                    // our object id in below line.
                    objectID = object.getObjectId().toString();
                     
                    // after getting our object id we will
                    // move towards updating our course.
                    // calling below method to update our course.
                    query.getInBackground(objectID, new GetCallback() {
                        @Override
                        public void done(ParseObject object, ParseException e) {
                            // in this method we are getting the
                            // object which we have to update.
                            if (e == null) {
                                 
                                // in below line we are adding new data
                                // to the object which we get from its id.
                                // on below line we are adding our data
                                // with their key value in our object.
                                object.put("courseName", courseName);
                                object.put("courseDescription", courseDescription);
                                object.put("courseDuration", courseDuration);
                                 
                                // after adding new data then we are
                                // calling a method to save this data
                                object.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 our data has been updated.
                                            // we are displaying a toast message and redirecting
                                            // our user to home activity where we are displaying course list.
                                            Toast.makeText(UpdateCourseActivity.this, "Course Updated..", Toast.LENGTH_SHORT).show();
                                            Intent i = new Intent(UpdateCourseActivity.this, HomeActivity.class);
                                            startActivity(i);
                                        } else {
                                            // below line is for error handling.
                                            Toast.makeText(UpdateCourseActivity.this, "Fail to update data " + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            } else {
                                // on below line we are displaying a message
                                // if we don't get the object from its id.
                                Toast.makeText(UpdateCourseActivity.this, "Fail to update course " + e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } else {
                    // this is error handling if we don't get the id for our object
                    Toast.makeText(UpdateCourseActivity.this, "Fail to get object ID..", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

现在运行您的应用程序,然后尝试更新您的课程。确保您以前已将一些课程添加到列表中。

输出:

以下是执行Update操作后Android Studio中的文件结构: