我们已经看到了如何在Android中创建数据并将其添加到SQLite数据库,以及如何在Android中从SQLite数据库读取数据。我们执行了不同的SQL查询,以将数据读取和写入SQLite数据库。在本文中,我们将研究如何在Android中将数据更新到SQLite数据库。
我们将在本文中构建什么?
我们将构建一个简单的应用程序,已在其中添加和读取数据。现在,我们将简单地在新活动中更新数据,然后我们就可以查看更新后的数据。下面提供了一个示例视频,以使您对本文中的工作有个大概的了解。注意,我们将使用Java语言实现该项目。
分步实施
第1步:创建新活动以更新我们的课程
由于我们要更新课程,因此在此过程中,我们将创建一个新活动,在该活动中我们将能够在SQLite数据库中更新我们的课程。要创建一个新的活动,我们必须导航到应用程序> Java >您的应用程序的包名称>右键单击包名称>新建>空活动,并将您的活动命名为UpdateCourseActivity并创建新的活动。确保选择空活动。
步骤2:使用activity_update_course.xml文件
导航到应用程序> res>布局> activity_update_course.xml,然后将以下代码添加到其中。
XML
Java
// below is the method for updating our courses
public void updateCourse(String originalCourseName, String courseName, String courseDescription,
String courseTracks, String courseDuration) {
// calling a method to get writable database.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// on below line we are passing all values
// along with its key and value pair.
values.put(NAME_COL, courseName);
values.put(DURATION_COL, courseDuration);
values.put(DESCRIPTION_COL, courseDescription);
values.put(TRACKS_COL, courseTracks);
// on below line we are calling a update method to update our database and passing our values.
// and we are comparing it with name of our course which is stored in original name variable.
db.update(TABLE_NAME, values, "name=?", new String[]{originalCourseName});
db.close();
}
Java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DBHandler extends SQLiteOpenHelper {
// creating a constant variables for our database.
// below variable is for our database name.
private static final String DB_NAME = "coursedb";
// below int is our database version
private static final int DB_VERSION = 1;
// below variable is for our table name.
private static final String TABLE_NAME = "mycourses";
// below variable is for our id column.
private static final String ID_COL = "id";
// below variable is for our course name column
private static final String NAME_COL = "name";
// below variable id for our course duration column.
private static final String DURATION_COL = "duration";
// below variable for our course description column.
private static final String DESCRIPTION_COL = "description";
// below variable is for our course tracks column.
private static final String TRACKS_COL = "tracks";
// creating a constructor for our database handler.
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
// below method is for creating a database by running a sqlite query
@Override
public void onCreate(SQLiteDatabase db) {
// on below line we are creating
// an sqlite query and we are
// setting our column names
// along with their data types.
String query = "CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COL + " TEXT,"
+ DURATION_COL + " TEXT,"
+ DESCRIPTION_COL + " TEXT,"
+ TRACKS_COL + " TEXT)";
// at last we are calling a exec sql
// method to execute above sql query
db.execSQL(query);
}
// this method is use to add new course to our sqlite database.
public void addNewCourse(String courseName, String courseDuration, String courseDescription, String courseTracks) {
// on below line we are creating a variable for
// our sqlite database and calling writable method
// as we are writing data in our database.
SQLiteDatabase db = this.getWritableDatabase();
// on below line we are creating a
// variable for content values.
ContentValues values = new ContentValues();
// on below line we are passing all values
// along with its key and value pair.
values.put(NAME_COL, courseName);
values.put(DURATION_COL, courseDuration);
values.put(DESCRIPTION_COL, courseDescription);
values.put(TRACKS_COL, courseTracks);
// after adding all values we are passing
// content values to our table.
db.insert(TABLE_NAME, null, values);
// at last we are closing our
// database after adding database.
db.close();
}
// we have created a new method for reading all the courses.
public ArrayList readCourses() {
// on below line we are creating a
// database for reading our database.
SQLiteDatabase db = this.getReadableDatabase();
// on below line we are creating a cursor with query to read data from database.
Cursor cursorCourses = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
// on below line we are creating a new array list.
ArrayList courseModalArrayList = new ArrayList<>();
// moving our cursor to first position.
if (cursorCourses.moveToFirst()) {
do {
// on below line we are adding the data from cursor to our array list.
courseModalArrayList.add(new CourseModal(cursorCourses.getString(1),
cursorCourses.getString(4),
cursorCourses.getString(2),
cursorCourses.getString(3)));
} while (cursorCourses.moveToNext());
// moving our cursor to next.
}
// at last closing our cursor
// and returning our array list.
cursorCourses.close();
return courseModalArrayList;
}
// below is the method for updating our courses
public void updateCourse(String originalCourseName, String courseName, String courseDescription,
String courseTracks, String courseDuration) {
// calling a method to get writable database.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// on below line we are passing all values
// along with its key and value pair.
values.put(NAME_COL, courseName);
values.put(DURATION_COL, courseDuration);
values.put(DESCRIPTION_COL, courseDescription);
values.put(TRACKS_COL, courseTracks);
// on below line we are calling a update method to update our database and passing our values.
// and we are comparing it with name of our course which is stored in original name variable.
db.update(TABLE_NAME, values, "name=?", new String[]{originalCourseName});
db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// this method is called to check if the table exists already.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
Java
// below line is to add on click listener for our recycler view item.
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// on below line we are calling an intent.
Intent i = new Intent(context, UpdateCourseActivity.class);
// below we are passing all our values.
i.putExtra("name", modal.getCourseName());
i.putExtra("description", modal.getCourseDescription());
i.putExtra("duration", modal.getCourseDuration());
i.putExtra("tracks", modal.getCourseTracks());
// 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 {
// variable for our array list and context
private ArrayList courseModalArrayList;
private Context context;
// constructor
public CourseRVAdapter(ArrayList courseModalArrayList, Context context) {
this.courseModalArrayList = courseModalArrayList;
this.context = context;
}
@NonNull
@Override
public 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 ViewHolder holder, int position) {
// on below line we are setting data
// to our views of recycler view item.
CourseModal modal = courseModalArrayList.get(position);
holder.courseNameTV.setText(modal.getCourseName());
holder.courseDescTV.setText(modal.getCourseDescription());
holder.courseDurationTV.setText(modal.getCourseDuration());
holder.courseTracksTV.setText(modal.getCourseTracks());
// below line is to add on click listener for our recycler view item.
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// on below line we are calling an intent.
Intent i = new Intent(context, UpdateCourseActivity.class);
// below we are passing all our values.
i.putExtra("name", modal.getCourseName());
i.putExtra("description", modal.getCourseDescription());
i.putExtra("duration", modal.getCourseDuration());
i.putExtra("tracks", modal.getCourseTracks());
// starting our activity.
context.startActivity(i);
}
});
}
@Override
public int getItemCount() {
// returning the size of our array list
return courseModalArrayList.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);
}
}
}
Java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class UpdateCourseActivity extends AppCompatActivity {
// variables for our edit text, button, strings and dbhandler class.
private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt;
private Button updateCourseBtn;
private DBHandler dbHandler;
String courseName, courseDesc, courseDuration, courseTracks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_course);
// initializing all our variables.
courseNameEdt = findViewById(R.id.idEdtCourseName);
courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
updateCourseBtn = findViewById(R.id.idBtnUpdateCourse);
// on below line we are initialing our dbhandler class.
dbHandler = new DBHandler(UpdateCourseActivity.this);
// on below lines we are getting data which
// we passed in our adapter class.
courseName = getIntent().getStringExtra("name");
courseDesc = getIntent().getStringExtra("description");
courseDuration = getIntent().getStringExtra("duration");
courseTracks = getIntent().getStringExtra("tracks");
// setting data to edit text
// of our update activity.
courseNameEdt.setText(courseName);
courseDescriptionEdt.setText(courseDesc);
courseTracksEdt.setText(courseTracks);
courseDurationEdt.setText(courseDuration);
// adding on click listener to our update course button.
updateCourseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// inside this method we are calling an update course
// method and passing all our edit text values.
dbHandler.updateCourse(courseName, courseNameEdt.getText().toString(), courseDescriptionEdt.getText().toString(), courseTracksEdt.getText().toString(), courseDurationEdt.getText().toString());
// displaying a toast message that our course has been updated.
Toast.makeText(UpdateCourseActivity.this, "Course Updated..", Toast.LENGTH_SHORT).show();
// launching our main activity.
Intent i = new Intent(UpdateCourseActivity.this, MainActivity.class);
startActivity(i);
}
});
}
}
步骤3:更新我们的DBHandler类
导航到应用程序> Java >应用程序的程序包名称> DBHandler,然后将以下代码添加到其中。在这种情况下,我们只需要创建一个新方法来更新我们的课程即可。
Java
// below is the method for updating our courses
public void updateCourse(String originalCourseName, String courseName, String courseDescription,
String courseTracks, String courseDuration) {
// calling a method to get writable database.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// on below line we are passing all values
// along with its key and value pair.
values.put(NAME_COL, courseName);
values.put(DURATION_COL, courseDuration);
values.put(DESCRIPTION_COL, courseDescription);
values.put(TRACKS_COL, courseTracks);
// on below line we are calling a update method to update our database and passing our values.
// and we are comparing it with name of our course which is stored in original name variable.
db.update(TABLE_NAME, values, "name=?", new String[]{originalCourseName});
db.close();
}
下面是DBHandler的更新代码。 Java文件 添加以上代码段后。
Java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class DBHandler extends SQLiteOpenHelper {
// creating a constant variables for our database.
// below variable is for our database name.
private static final String DB_NAME = "coursedb";
// below int is our database version
private static final int DB_VERSION = 1;
// below variable is for our table name.
private static final String TABLE_NAME = "mycourses";
// below variable is for our id column.
private static final String ID_COL = "id";
// below variable is for our course name column
private static final String NAME_COL = "name";
// below variable id for our course duration column.
private static final String DURATION_COL = "duration";
// below variable for our course description column.
private static final String DESCRIPTION_COL = "description";
// below variable is for our course tracks column.
private static final String TRACKS_COL = "tracks";
// creating a constructor for our database handler.
public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
// below method is for creating a database by running a sqlite query
@Override
public void onCreate(SQLiteDatabase db) {
// on below line we are creating
// an sqlite query and we are
// setting our column names
// along with their data types.
String query = "CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME_COL + " TEXT,"
+ DURATION_COL + " TEXT,"
+ DESCRIPTION_COL + " TEXT,"
+ TRACKS_COL + " TEXT)";
// at last we are calling a exec sql
// method to execute above sql query
db.execSQL(query);
}
// this method is use to add new course to our sqlite database.
public void addNewCourse(String courseName, String courseDuration, String courseDescription, String courseTracks) {
// on below line we are creating a variable for
// our sqlite database and calling writable method
// as we are writing data in our database.
SQLiteDatabase db = this.getWritableDatabase();
// on below line we are creating a
// variable for content values.
ContentValues values = new ContentValues();
// on below line we are passing all values
// along with its key and value pair.
values.put(NAME_COL, courseName);
values.put(DURATION_COL, courseDuration);
values.put(DESCRIPTION_COL, courseDescription);
values.put(TRACKS_COL, courseTracks);
// after adding all values we are passing
// content values to our table.
db.insert(TABLE_NAME, null, values);
// at last we are closing our
// database after adding database.
db.close();
}
// we have created a new method for reading all the courses.
public ArrayList readCourses() {
// on below line we are creating a
// database for reading our database.
SQLiteDatabase db = this.getReadableDatabase();
// on below line we are creating a cursor with query to read data from database.
Cursor cursorCourses = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
// on below line we are creating a new array list.
ArrayList courseModalArrayList = new ArrayList<>();
// moving our cursor to first position.
if (cursorCourses.moveToFirst()) {
do {
// on below line we are adding the data from cursor to our array list.
courseModalArrayList.add(new CourseModal(cursorCourses.getString(1),
cursorCourses.getString(4),
cursorCourses.getString(2),
cursorCourses.getString(3)));
} while (cursorCourses.moveToNext());
// moving our cursor to next.
}
// at last closing our cursor
// and returning our array list.
cursorCourses.close();
return courseModalArrayList;
}
// below is the method for updating our courses
public void updateCourse(String originalCourseName, String courseName, String courseDescription,
String courseTracks, String courseDuration) {
// calling a method to get writable database.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// on below line we are passing all values
// along with its key and value pair.
values.put(NAME_COL, courseName);
values.put(DURATION_COL, courseDuration);
values.put(DESCRIPTION_COL, courseDescription);
values.put(TRACKS_COL, courseTracks);
// on below line we are calling a update method to update our database and passing our values.
// and we are comparing it with name of our course which is stored in original name variable.
db.update(TABLE_NAME, values, "name=?", new String[]{originalCourseName});
db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// this method is called to check if the table exists already.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
步骤4:更新我们的CourseRVAdapter。 Java类
我们将开始一项新的活动,以更新我们的课程。我们必须在单击侦听器上添加RecycleView的项目。要将onClickListener()添加到我们的回收站视图项目,请导航至应用程序> Java >您的应用程序的程序包名称> CourseRVAdapter类,并只需为我们的RecyclerView项目添加一个onClickListener () 。将以下代码添加到您的适配器类。
Java
// below line is to add on click listener for our recycler view item.
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// on below line we are calling an intent.
Intent i = new Intent(context, UpdateCourseActivity.class);
// below we are passing all our values.
i.putExtra("name", modal.getCourseName());
i.putExtra("description", modal.getCourseDescription());
i.putExtra("duration", modal.getCourseDuration());
i.putExtra("tracks", modal.getCourseTracks());
// 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 {
// variable for our array list and context
private ArrayList courseModalArrayList;
private Context context;
// constructor
public CourseRVAdapter(ArrayList courseModalArrayList, Context context) {
this.courseModalArrayList = courseModalArrayList;
this.context = context;
}
@NonNull
@Override
public 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 ViewHolder holder, int position) {
// on below line we are setting data
// to our views of recycler view item.
CourseModal modal = courseModalArrayList.get(position);
holder.courseNameTV.setText(modal.getCourseName());
holder.courseDescTV.setText(modal.getCourseDescription());
holder.courseDurationTV.setText(modal.getCourseDuration());
holder.courseTracksTV.setText(modal.getCourseTracks());
// below line is to add on click listener for our recycler view item.
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// on below line we are calling an intent.
Intent i = new Intent(context, UpdateCourseActivity.class);
// below we are passing all our values.
i.putExtra("name", modal.getCourseName());
i.putExtra("description", modal.getCourseDescription());
i.putExtra("duration", modal.getCourseDuration());
i.putExtra("tracks", modal.getCourseTracks());
// starting our activity.
context.startActivity(i);
}
});
}
@Override
public int getItemCount() {
// returning the size of our array list
return courseModalArrayList.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);
}
}
}
步骤5:使用UpdateCourseActivity。 Java文件
导航到应用程序> Java >您的应用程序包名称> UpdateCourseActivity。 Java文件,并向其中添加以下代码。在代码内部添加了注释,以更详细地了解代码。
Java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class UpdateCourseActivity extends AppCompatActivity {
// variables for our edit text, button, strings and dbhandler class.
private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt;
private Button updateCourseBtn;
private DBHandler dbHandler;
String courseName, courseDesc, courseDuration, courseTracks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_course);
// initializing all our variables.
courseNameEdt = findViewById(R.id.idEdtCourseName);
courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
updateCourseBtn = findViewById(R.id.idBtnUpdateCourse);
// on below line we are initialing our dbhandler class.
dbHandler = new DBHandler(UpdateCourseActivity.this);
// on below lines we are getting data which
// we passed in our adapter class.
courseName = getIntent().getStringExtra("name");
courseDesc = getIntent().getStringExtra("description");
courseDuration = getIntent().getStringExtra("duration");
courseTracks = getIntent().getStringExtra("tracks");
// setting data to edit text
// of our update activity.
courseNameEdt.setText(courseName);
courseDescriptionEdt.setText(courseDesc);
courseTracksEdt.setText(courseTracks);
courseDurationEdt.setText(courseDuration);
// adding on click listener to our update course button.
updateCourseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// inside this method we are calling an update course
// method and passing all our edit text values.
dbHandler.updateCourse(courseName, courseNameEdt.getText().toString(), courseDescriptionEdt.getText().toString(), courseTracksEdt.getText().toString(), courseDurationEdt.getText().toString());
// displaying a toast message that our course has been updated.
Toast.makeText(UpdateCourseActivity.this, "Course Updated..", Toast.LENGTH_SHORT).show();
// launching our main activity.
Intent i = new Intent(UpdateCourseActivity.this, MainActivity.class);
startActivity(i);
}
});
}
}
现在运行您的应用程序,并查看该应用程序的输出。确保在更新数据之前将数据添加到SQLite数据库。
输出:
下面是执行更新操作后的完整项目文件结构: