实验四:SQLite和SQLiteDatabase应用

好的!根据实验四的要求,我们将实现一个Android应用程序,用于录入和管理个人信息,并通过SQLite数据库实现数据的增删改查操作。我们将实现以下功能:

1. **录入个人信息**:姓名、年龄、邮箱。
2. **显示个人信息列表**。
3. **删除个人信息**。
4. **更新个人信息**。

以下是完整的代码实现:

### 1. 创建项目
在Android Studio中创建一个新的项目,命名为`Database`,选择一个空的Activity模板。

### 2. 布局文件
#### 修改`activity_main.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"
android:padding="16dp">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名:"
android:textSize="18sp" />

<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入姓名" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="年龄:"
android:textSize="18sp" />

<EditText
android:id="@+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入年龄"
android:inputType="number" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="邮箱:"
android:textSize="18sp" />

<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入邮箱" />

<Button
android:id="@+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加" />

<Button
android:id="@+id/view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查看列表" />
</LinearLayout>
```

#### 创建`activity_display.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"
android:padding="16dp">

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
```

### 3. 创建Activity
#### 修改`MainActivity.java`
```java
package com.example.database;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
private EditText nameEditText;
private EditText ageEditText;
private EditText emailEditText;
private Button addButton;
private Button viewButton;
private DBHelper dbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

nameEditText = findViewById(R.id.name);
ageEditText = findViewById(R.id.age);
emailEditText = findViewById(R.id.email);
addButton = findViewById(R.id.add);
viewButton = findViewById(R.id.view);

dbHelper = new DBHelper(this);

addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = nameEditText.getText().toString();
String age = ageEditText.getText().toString();
String email = emailEditText.getText().toString();

if (!name.isEmpty() && !age.isEmpty() && !email.isEmpty()) {
dbHelper.addPerson(name, age, email);
nameEditText.setText("");
ageEditText.setText("");
emailEditText.setText("");
}
}
});

viewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
startActivity(intent);
}
});
}
}
```

#### 创建`DisplayActivity.java`
```java
package com.example.database;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class DisplayActivity extends AppCompatActivity {
private ListView listView;
private DBHelper dbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);

listView = findViewById(R.id.listView);
dbHelper = new DBHelper(this);

ArrayList<String> personList = dbHelper.getAllPersons();
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, personList);
listView.setAdapter(adapter);

listView.setOnItemClickListener((parent, view, position, id) -> {
String person = personList.get(position);
new AlertDialog.Builder(DisplayActivity.this)
.setTitle("删除")
.setMessage("是否删除这条记录?")
.setPositiveButton("删除", (dialog, which) -> {
dbHelper.deletePerson(person.split(", ")[0]); // 删除姓名
personList.remove(position);
adapter.notifyDataSetChanged();
})
.setNegativeButton("取消", null)
.show();
});
}
}
```

#### 创建`DBHelper.java`
```java
package com.example.database;

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 DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "PersonDB";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_PERSON = "person";
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 COLUMN_EMAIL = "email";

public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_PERSON = "CREATE TABLE " + TABLE_PERSON + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_AGE + " TEXT,"
+ COLUMN_EMAIL + " TEXT)";
db.execSQL(CREATE_TABLE_PERSON);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PERSON);
onCreate(db);
}

public void addPerson(String name, String age, String email) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
values.put(COLUMN_AGE, age);
values.put(COLUMN_EMAIL, email);
db.insert(TABLE_PERSON, null, values);
db.close();
}

public ArrayList<String> getAllPersons() {
ArrayList<String> personList = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_PERSON;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));
String age = cursor.getString(cursor.getColumnIndex(COLUMN_AGE));
String email = cursor.getString(cursor.getColumnIndex(COLUMN_EMAIL));
personList.add("姓名: " + name + ", 年龄: " + age + ", 邮箱: " + email);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return personList;
}

public void deletePerson(String name) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_PERSON, COLUMN_NAME + " = ?", new String[]{name});
db.close();
}
}
```

### 4. 确保`AndroidManifest.xml`文件正确
确保在`AndroidManifest.xml`中注册了`DisplayActivity`:
```xml
<application
...>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DisplayActivity" />
</application>
```

### 5. 运行程序
1. 在Android Studio中运行程序。
2. 在主界面输入姓名、年龄和邮箱,点击“添加”按钮将信息存入数据库。
3. 点击“查看列表”按钮,进入列表页面显示所有个人信息。
4. 点击列表中的某一项,会弹出对话框询问是否删除该记录。

### 功能说明
- **添加**:将用户输入的姓名、年龄和邮箱存入数据库。
- **查看列表**:从数据库中读取所有个人信息并显示在列表中。
- **删除**:点击列表项时弹出对话框,确认后删除指定记录。

### 注意事项
- 确保在`activity_main.xml`中正确

posted @ 2025-04-07 09:21  新晋软工小白  阅读(51)  评论(0)    收藏  举报