案例5-3,编写程序演示sqlite数据库操作。android
时间: 2024-03-24 08:37:01 浏览: 29
以下是一个简单的 Android 应用程序,演示如何使用 SQLite 数据库进行 CRUD 操作:
1. 创建一个新的 Android 项目,并在 build.gradle 文件中添加以下依赖:
```groovy
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.sqlite:sqlite:2.1.0'
}
```
2. 创建一个新的数据库帮助器类 DBHelper,继承自 SQLiteOpenHelper:
```java
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "my_db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "my_table";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_AGE = "age";
private static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME +
" (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_AGE + " INTEGER" +
")";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
3. 在 MainActivity 中,初始化 DBHelper 实例,并使用 SQLiteDatabase 实例进行 CRUD 操作:
```java
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<Person> personList = new ArrayList<>();
private DBHelper dbHelper;
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DBHelper(this);
db = dbHelper.getWritableDatabase();
recyclerView = findViewById(R.id.recycler_view);
adapter = new PersonAdapter(personList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
findViewById(R.id.button_add).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addPerson();
}
});
findViewById(R.id.button_query).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
queryPerson();
}
});
}
private void addPerson() {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, "Tom");
values.put(DBHelper.COLUMN_AGE, 20);
db.insert(DBHelper.TABLE_NAME, null, values);
}
private void queryPerson() {
Cursor cursor = db.query(DBHelper.TABLE_NAME, null, null, null, null, null, null);
if (cursor.moveToFirst()) {
personList.clear();
do {
int id = cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME));
int age = cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_AGE));
Person person = new Person(id, name, age);
personList.add(person);
} while (cursor.moveToNext());
adapter.notifyDataSetChanged();
}
cursor.close();
}
@Override
protected void onDestroy() {
super.onDestroy();
db.close();
dbHelper.close();
}
}
```
4. 创建一个 Person 类,用来封装数据库中的每一条记录:
```java
public class Person {
private int id;
private String name;
private int age;
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
5. 创建一个 RecyclerView.Adapter 类,用来展示数据库中的每一条记录:
```java
public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.ViewHolder> {
private List<Person> personList;
public PersonAdapter(List<Person> personList) {
this.personList = personList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_person, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Person person = personList.get(position);
holder.textViewId.setText(String.valueOf(person.getId()));
holder.textViewName.setText(person.getName());
holder.textViewAge.setText(String.valueOf(person.getAge()));
}
@Override
public int getItemCount() {
return personList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView textViewId;
TextView textViewName;
TextView textViewAge;
public ViewHolder(@NonNull View itemView) {
super(itemView);
textViewId = itemView.findViewById(R.id.text_view_id);
textViewName = itemView.findViewById(R.id.text_view_name);
textViewAge = itemView.findViewById(R.id.text_view_age);
}
}
}
```
6. 创建一个 item_person.xml 布局文件,用来展示每一条记录:
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<TextView
android:id="@+id/text_view_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ID"/>
<TextView
android:id="@+id/text_view_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Name"/>
<TextView
android:id="@+id/text_view_age"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Age"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
```
7. 运行应用程序,点击“Add”按钮添加一条记录,点击“Query”按钮查询所有记录,并展示在 RecyclerView 中。
以上就是一个简单的 Android 应用程序,演示如何使用 SQLite 数据库进行 CRUD 操作。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)