用android的sqllite数据库写一个古诗词的增、删、查、改,写清楚布局文件、Java文件等相关代码
时间: 2023-07-10 14:03:50 浏览: 129
androdi简单操作数据库入门.txt
好的,下面是一个简单的古诗词增删查改的示例,使用 SQLite 数据库存储数据。
首先,需要在 Android Studio 中创建一个新项目,然后在 app 目录下的 build.gradle 文件中添加以下依赖项:
```
implementation 'androidx.recyclerview:recyclerview:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.sqlite:sqlite:2.1.0'
```
接下来,我们需要创建一个数据库帮助类 DBHelper.java,用于创建数据库和表格,并提供增删查改操作。
```java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "poetry.db";
private static final int DB_VERSION = 1;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS poetry (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, author TEXT, content TEXT)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS poetry");
onCreate(db);
}
public void insert(String title, String author, String content) {
SQLiteDatabase db = getWritableDatabase();
String sql = "INSERT INTO poetry (title, author, content) VALUES (?, ?, ?)";
db.execSQL(sql, new String[]{title, author, content});
db.close();
}
public void delete(int id) {
SQLiteDatabase db = getWritableDatabase();
String sql = "DELETE FROM poetry WHERE _id=?";
db.execSQL(sql, new Object[]{id});
db.close();
}
public void update(int id, String title, String author, String content) {
SQLiteDatabase db = getWritableDatabase();
String sql = "UPDATE poetry SET title=?, author=?, content=? WHERE _id=?";
db.execSQL(sql, new Object[]{title, author, content, id});
db.close();
}
public Cursor queryAll() {
SQLiteDatabase db = getReadableDatabase();
String sql = "SELECT * FROM poetry";
Cursor cursor = db.rawQuery(sql, null);
return cursor;
}
}
```
接下来,我们需要创建一个显示诗词列表的界面 PoetryListActivity.java,以及一个用于显示每首诗词的界面 PoetryDetailActivity.java。
```java
public class PoetryListActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private PoetryListAdapter mAdapter;
private List<Poetry> mDataList = new ArrayList<>();
private DBHelper mDBHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poetry_list);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new PoetryListAdapter(this, mDataList);
mRecyclerView.setAdapter(mAdapter);
mDBHelper = new DBHelper(this);
loadData();
}
private void loadData() {
mDataList.clear();
Cursor cursor = mDBHelper.queryAll();
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String title = cursor.getString(cursor.getColumnIndex("title"));
String author = cursor.getString(cursor.getColumnIndex("author"));
String content = cursor.getString(cursor.getColumnIndex("content"));
Poetry poetry = new Poetry(id, title, author, content);
mDataList.add(poetry);
}
mAdapter.notifyDataSetChanged();
}
public void onAddClick(View view) {
startActivity(new Intent(this, PoetryDetailActivity.class));
}
@Override
protected void onResume() {
super.onResume();
loadData();
}
}
```
```java
public class PoetryDetailActivity extends AppCompatActivity {
private EditText mTitleEditText;
private EditText mAuthorEditText;
private EditText mContentEditText;
private DBHelper mDBHelper;
private int mPoetryId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poetry_detail);
mTitleEditText = findViewById(R.id.title_edit_text);
mAuthorEditText = findViewById(R.id.author_edit_text);
mContentEditText = findViewById(R.id.content_edit_text);
mDBHelper = new DBHelper(this);
mPoetryId = getIntent().getIntExtra("poetry_id", -1);
if (mPoetryId != -1) {
Cursor cursor = mDBHelper.queryById(mPoetryId);
if (cursor.moveToFirst()) {
String title = cursor.getString(cursor.getColumnIndex("title"));
String author = cursor.getString(cursor.getColumnIndex("author"));
String content = cursor.getString(cursor.getColumnIndex("content"));
mTitleEditText.setText(title);
mAuthorEditText.setText(author);
mContentEditText.setText(content);
}
}
}
public void onSaveClick(View view) {
String title = mTitleEditText.getText().toString();
String author = mAuthorEditText.getText().toString();
String content = mContentEditText.getText().toString();
if (mPoetryId == -1) {
mDBHelper.insert(title, author, content);
} else {
mDBHelper.update(mPoetryId, title, author, content);
}
finish();
}
public void onDeleteClick(View view) {
if (mPoetryId != -1) {
mDBHelper.delete(mPoetryId);
}
finish();
}
}
```
最后,我们需要在布局文件中添加以下内容:
activity_poetry_list.xml
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:onClick="onAddClick"
android:text="添加诗词" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
```
activity_poetry_detail.xml
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/title_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="题目" />
<EditText
android:id="@+id/author_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="作者" />
<EditText
android:id="@+id/content_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="内容" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/save_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onSaveClick"
android:text="保存" />
<Button
android:id="@+id/delete_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onDeleteClick"
android:text="删除" />
</LinearLayout>
</LinearLayout>
```
最后,我们需要创建一个用于显示诗词列表的适配器 PoetryListAdapter.java。
```java
public class PoetryListAdapter extends RecyclerView.Adapter<PoetryListAdapter.ViewHolder> {
private Context mContext;
private List<Poetry> mDataList;
public PoetryListAdapter(Context context, List<Poetry> dataList) {
mContext = context;
mDataList = dataList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_poetry, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final Poetry poetry = mDataList.get(position);
holder.titleTextView.setText(poetry.getTitle());
holder.authorTextView.setText(poetry.getAuthor());
holder.contentTextView.setText(poetry.getContent());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, PoetryDetailActivity.class);
intent.putExtra("poetry_id", poetry.getId());
mContext.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return mDataList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView titleTextView;
TextView authorTextView;
TextView contentTextView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.title_text_view);
authorTextView = itemView.findViewById(R.id.author_text_view);
contentTextView = itemView.findViewById(R.id.content_text_view);
}
}
}
```
最后,我们在 res/values/styles.xml 文件中添加以下样式:
```xml
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<item name="android:fontFamily">@font/roboto</item>
</style>
```
最后,我们还需要在 AndroidManifest.xml 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
阅读全文