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

📅  最后修改于: 2021-05-10 14:02:25             🧑  作者: Mango

在先前的文章中,我们已经看到了在Android的领域数据库中添加和读取数据。在那篇文章中,我们在数据库中添加了课程详细信息,并以列表的形式读取了数据。在本文中,我们将看看在我们的android应用程序更新此数据。

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

我们将处理在先前文章中构建的现有应用程序。这样,我们将简单地创建一个新活动,即创建一个表单来更新我们的课程详细信息。下面是视频,我们将在其中观看我们将要构建的内容。

分步实施

第1步创建新活动以更新我们的课程

由于我们要更新课程,因此在此过程中,我们将创建一个新活动,在该活动中我们将能够在SQLite数据库中更新我们的课程。要创建一个新的活动,我们必须导航到应用程序> Java >您的应用程序的包名称>右键单击包名称>新建>空活动,并将您的活动命名为UpdateCourseActivity并创建新的活动。确保选择空活动

步骤2:更新我们的CourseRVAdapter。 Java类

我们将开始一项新的活动,以更新我们的课程。我们必须在单击侦听器上添加RecycleView的项目。要将onClickListener()添加到我们的回收站视图项目,请导航至应用程序> Java >您的应用程序的程序包名称> CourseRVAdapter类,并只需为我们的RecyclerView项目添加一个onClickListener () 。将以下代码添加到您的适配器类。

Java
// adding on click listener for item of recycler view.
holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // on below line we are creating a new intent.
                Intent i = new Intent(context, UpdateCourseActivity.class);
                // on below line we are passing all the data to new activity.
                i.putExtra("courseName", modal.getCourseName());
                i.putExtra("courseDescription", modal.getCourseDescription());
                i.putExtra("courseDuration", modal.getCourseDuration());
                i.putExtra("courseTracks", modal.getCourseTracks());
                i.putExtra("id", modal.getId());
                // on below line we are starting a new 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.List;
 
public class CourseRVAdapter extends RecyclerView.Adapter {
 
    // variable for our array list and context
    private List dataModalArrayList;
    private Context context;
 
    public CourseRVAdapter(List dataModalArrayList, Context context) {
        this.dataModalArrayList = dataModalArrayList;
        this.context = context;
    }
 
    @NonNull
    @Override
    public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // on below line we are inflating our layout
        // file for our recycler view items.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
        return new ViewHolder(view);
    }
 
    @Override
    public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {
        DataModal modal = dataModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getCourseName());
        holder.courseDescTV.setText(modal.getCourseDescription());
        holder.courseDurationTV.setText(modal.getCourseDuration());
        holder.courseTracksTV.setText(modal.getCourseTracks());
 
        // adding on click listener for item of recycler view.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // on below line we are creating a new intent.
                Intent i = new Intent(context, UpdateCourseActivity.class);
                // on below line we are passing all the data to new activity.
                i.putExtra("courseName", modal.getCourseName());
                i.putExtra("courseDescription", modal.getCourseDescription());
                i.putExtra("courseDuration", modal.getCourseDuration());
                i.putExtra("courseTracks", modal.getCourseTracks());
                i.putExtra("id", modal.getId());
                // on below line we are starting a new activity.
                context.startActivity(i);
            }
        });
    }
 
    @Override
    public int getItemCount() {
        return dataModalArrayList.size();
    }
 
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our text views.
        private TextView courseNameTV, courseDescTV, courseDurationTV, courseTracksTV;
 
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our text views
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
            courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);
            courseTracksTV = itemView.findViewById(R.id.idTVCourseTracks);
        }
    }
}


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 io.realm.Realm;
 
public class UpdateCourseActivity extends AppCompatActivity {
     
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt, courseTracksEdt;
     
    // creating a strings for storing
    // our values from edittext fields.
    private String courseName, courseDuration, courseDescription, courseTracks;
    private long id;
    private Button updateCourseBtn;
    private Realm realm;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_course);
         
        // initializing our edittext and buttons
        realm = Realm.getDefaultInstance();
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
        courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
        updateCourseBtn = findViewById(R.id.idBtnUpdateCourse);
         
        // on below line we are getting data which is passed from intent.
        courseName = getIntent().getStringExtra("courseName");
        courseDuration = getIntent().getStringExtra("courseDuration");
        courseDescription = getIntent().getStringExtra("courseDescription");
        courseTracks = getIntent().getStringExtra("courseTracks");
        id = getIntent().getLongExtra("id", 0);
         
        // on below line we are setting data in our edit test fields.
        courseNameEdt.setText(courseName);
        courseDurationEdt.setText(courseDuration);
        courseDescriptionEdt.setText(courseDescription);
        courseTracksEdt.setText(courseTracks);
         
        // adding on click listener for update button.
        updateCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 
                // getting data from edittext fields.
                String courseName = courseNameEdt.getText().toString();
                String courseDescription = courseDescriptionEdt.getText().toString();
                String courseDuration = courseDurationEdt.getText().toString();
                String courseTracks = courseTracksEdt.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 if (TextUtils.isEmpty(courseTracks)) {
                    courseTracksEdt.setError("Please enter Course Tracks");
                } else {
                    // on below line we are getting data from our modal where
                    // the id of the course equals to which we passed previously.
                    final DataModal modal = realm.where(DataModal.class).equalTo("id", id).findFirst();
                    updateCourse(modal, courseName, courseDescription, courseDuration, courseTracks);
                }
                 
                // on below line we are displaying a toast message when course is updated.
                Toast.makeText(UpdateCourseActivity.this, "Course Updated.", Toast.LENGTH_SHORT).show();
                 
                // on below line we are opening our activity for read course activity to view updated course.
                Intent i = new Intent(UpdateCourseActivity.this, ReadCoursesActivity.class);
                startActivity(i);
                finish();
            }
        });
    }
 
    private void updateCourse(DataModal modal, String courseName, String courseDescription, String courseDuration, String courseTracks) {
 
        // on below line we are calling
        // a method to execute a transaction.
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                 
                // on below line we are setting data to our modal class
                // which we get from our edit text fields.
                modal.setCourseDescription(courseDescription);
                modal.setCourseName(courseName);
                modal.setCourseDuration(courseDuration);
                modal.setCourseTracks(courseTracks);
                 
                // inside on execute method we are calling a method to copy
                // and update to real m database from our modal class.
                realm.copyToRealmOrUpdate(modal);
            }
        });
    }
}


下面是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.List;
 
public class CourseRVAdapter extends RecyclerView.Adapter {
 
    // variable for our array list and context
    private List dataModalArrayList;
    private Context context;
 
    public CourseRVAdapter(List dataModalArrayList, Context context) {
        this.dataModalArrayList = dataModalArrayList;
        this.context = context;
    }
 
    @NonNull
    @Override
    public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // on below line we are inflating our layout
        // file for our recycler view items.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
        return new ViewHolder(view);
    }
 
    @Override
    public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {
        DataModal modal = dataModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getCourseName());
        holder.courseDescTV.setText(modal.getCourseDescription());
        holder.courseDurationTV.setText(modal.getCourseDuration());
        holder.courseTracksTV.setText(modal.getCourseTracks());
 
        // adding on click listener for item of recycler view.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // on below line we are creating a new intent.
                Intent i = new Intent(context, UpdateCourseActivity.class);
                // on below line we are passing all the data to new activity.
                i.putExtra("courseName", modal.getCourseName());
                i.putExtra("courseDescription", modal.getCourseDescription());
                i.putExtra("courseDuration", modal.getCourseDuration());
                i.putExtra("courseTracks", modal.getCourseTracks());
                i.putExtra("id", modal.getId());
                // on below line we are starting a new activity.
                context.startActivity(i);
            }
        });
    }
 
    @Override
    public int getItemCount() {
        return dataModalArrayList.size();
    }
 
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our text views.
        private TextView courseNameTV, courseDescTV, courseDurationTV, courseTracksTV;
 
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our text views
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
            courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);
            courseTracksTV = itemView.findViewById(R.id.idTVCourseTracks);
        }
    }
}

步骤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 io.realm.Realm;
 
public class UpdateCourseActivity extends AppCompatActivity {
     
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt, courseTracksEdt;
     
    // creating a strings for storing
    // our values from edittext fields.
    private String courseName, courseDuration, courseDescription, courseTracks;
    private long id;
    private Button updateCourseBtn;
    private Realm realm;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_course);
         
        // initializing our edittext and buttons
        realm = Realm.getDefaultInstance();
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
        courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
        updateCourseBtn = findViewById(R.id.idBtnUpdateCourse);
         
        // on below line we are getting data which is passed from intent.
        courseName = getIntent().getStringExtra("courseName");
        courseDuration = getIntent().getStringExtra("courseDuration");
        courseDescription = getIntent().getStringExtra("courseDescription");
        courseTracks = getIntent().getStringExtra("courseTracks");
        id = getIntent().getLongExtra("id", 0);
         
        // on below line we are setting data in our edit test fields.
        courseNameEdt.setText(courseName);
        courseDurationEdt.setText(courseDuration);
        courseDescriptionEdt.setText(courseDescription);
        courseTracksEdt.setText(courseTracks);
         
        // adding on click listener for update button.
        updateCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 
                // getting data from edittext fields.
                String courseName = courseNameEdt.getText().toString();
                String courseDescription = courseDescriptionEdt.getText().toString();
                String courseDuration = courseDurationEdt.getText().toString();
                String courseTracks = courseTracksEdt.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 if (TextUtils.isEmpty(courseTracks)) {
                    courseTracksEdt.setError("Please enter Course Tracks");
                } else {
                    // on below line we are getting data from our modal where
                    // the id of the course equals to which we passed previously.
                    final DataModal modal = realm.where(DataModal.class).equalTo("id", id).findFirst();
                    updateCourse(modal, courseName, courseDescription, courseDuration, courseTracks);
                }
                 
                // on below line we are displaying a toast message when course is updated.
                Toast.makeText(UpdateCourseActivity.this, "Course Updated.", Toast.LENGTH_SHORT).show();
                 
                // on below line we are opening our activity for read course activity to view updated course.
                Intent i = new Intent(UpdateCourseActivity.this, ReadCoursesActivity.class);
                startActivity(i);
                finish();
            }
        });
    }
 
    private void updateCourse(DataModal modal, String courseName, String courseDescription, String courseDuration, String courseTracks) {
 
        // on below line we are calling
        // a method to execute a transaction.
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                 
                // on below line we are setting data to our modal class
                // which we get from our edit text fields.
                modal.setCourseDescription(courseDescription);
                modal.setCourseName(courseName);
                modal.setCourseDuration(courseDuration);
                modal.setCourseTracks(courseTracks);
                 
                // inside on execute method we are calling a method to copy
                // and update to real m database from our modal class.
                realm.copyToRealmOrUpdate(modal);
            }
        });
    }
}

现在运行您的应用程序,并查看该应用程序的输出:

输出:

下面是执行更新操作后的完整项目文件结构: