本次实验的目的是让大家熟悉 Android 中对数据库进行操作的相关的接口、类等。SQLiteDatabase 这个是在 android 中数据库操作使用最频繁的一个类。通过它可以实现数据库的创建或打开、创建表、插入数据、删除数据、查询数据、修改数据等操作。
创建一个名为"便签管理系统"的Android项目,包含以下文件和文件夹:
activity_main.xml
(启动窗体)insertinfo.xml
(新增便签窗体)showinfo.xml
(查看便签信息窗体)manageflag.xml
(便签管理窗体)MainActivity.java
(主活动)InsertFlag.java
(新增便签活动)ShowInfo.java
(查看便签信息活动)ManageFlag.java
(便签管理活动)DBOpenHelper.java
(数据库帮助类)FlagDao.java
(便签数据访问类)flag.java
(便签实体类)AndroidManifest.xml
(清单文件)activity_main.xml (启动窗体)
包含两个按钮:btnflaginfo
(查看便签信息) 和 btninsertinfo
(添加便签)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.06"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/btnflaginfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="便签信息"
android:textColor="#8C6931"
android:textSize="20dp" />
<Button
android:id="@+id/btninsertinfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/btnflaginfo"
android:text="添加便签"
android:textColor="#8C6931"
android:textSize="20dp" />
RelativeLayout>
LinearLayout>
LinearLayout>
Insertinfo.xml (新增便签窗体)
包含一个文本框 txtFlag
用于输入便签内容
包含两个按钮:btnflagSave
(保存) 和 btnflagCancel
(取消)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/itemflag"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="3"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="新增便签"
android:textColor="#000000"
android:textSize="40sp"
android:textStyle="bold" />
LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<TextView
android:id="@+id/tvFlag"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="请输入便签,最多输入 200 字"
android:textColor="#8C6931"
android:textSize="23sp" />
<EditText
android:id="@+id/txtFlag"
android:layout_width="350dp"
android:layout_height="400dp"
android:layout_below="@id/tvFlag"
android:gravity="top"
android:singleLine="false" />
RelativeLayout>
LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="3"
android:orientation="vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<Button
android:id="@+id/btnflagCancel"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:text="取消" />
<Button
android:id="@+id/btnflagSave"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/btnflagCancel"
android:maxLength="200"
android:text="保存" />
RelativeLayout>
LinearLayout>
LinearLayout>
showinfo.xml (查看便签信息窗体)
textView1
和一个列表视图 lvinfo
用于展示便签信息
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="便签信息"
android:textSize="20dp" />
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.94"
android:orientation="vertical">
<ListView
android:id="@+id/lvinfo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbarAlwaysDrawVerticalTrack="true" />
LinearLayout>
LinearLayout>
manageflag.xml (便签管理窗体)
txtFlagManage
和两个按钮:btnFlagManageEdit
(修改) 和 btnFlagManageDelete
(删除)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/flagmanage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="3"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="便签管理"
android:textColor="#000000"
android:textSize="40sp"
android:textStyle="bold" />
LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<TextView
android:id="@+id/tvFlagManage"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="请输入便签,最多输入 200 字"
android:textColor="#8C6931"
android:textSize="23sp" />
<EditText
android:id="@+id/txtFlagManage"
android:layout_width="350dp"
android:layout_height="400dp"
android:layout_below="@id/tvFlagManage"
android:gravity="top"
android:singleLine="false" />
RelativeLayout>
LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="3"
android:orientation="vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<Button
android:id="@+id/btnFlagManageDelete"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:text="删除" />
<Button
android:id="@+id/btnFlagManageEdit"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/btnFlagManageDelete"
android:maxLength="200"
android:text="修改" />
RelativeLayout>
LinearLayout>
LinearLayout>
MainActivity.java
ShowInfo
和 InsertFlag
活动package com.example.notemanagementsystem.activity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.wenlong.DBLab.activity.R;
public class MainActivity extends Activity {
Button btnflaginfo, btninsertinfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnflaginfo = (Button) findViewById(R.id.btnflaginfo);
btninsertinfo = (Button) findViewById(R.id.btninsertinfo);
btnflaginfo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ShowInfo.class);
startActivity(intent);
}
});
btninsertinfo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, InsertFlag.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
InsertFlag.java
package com.example.notemanagementsystem;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.notemanagementsystem.DAO.FlagDao;
import com.example.notemanagementsystem.model.flag;
public class InsertFlag extends Activity {
EditText txtFlag;// 创建 EditText 组件对象
Button btnflagSaveButton;// 创建 Button 组件对象
Button btnflagCancelButton;// 创建 Button 组件对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.insertinfo);
txtFlag = (EditText) findViewById(R.id.txtFlag);
btnflagSaveButton = (Button) findViewById(R.id.btnflagSave);
btnflagCancelButton = (Button) findViewById(R.id.btnflagCancel);
btnflagSaveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String strFlag = txtFlag.getText().toString();// 获取便签文本框的值
if (!strFlag.isEmpty()) {// 判断获取
FlagDao flagDAO = new FlagDao(InsertFlag.this);// 创建FlagDAO 对象
flag flag = new flag(
flagDAO.getMaxId() + 1, strFlag);// 创建 Tb_flag 对象
flagDAO.add(flag);// 添加便签信息
// 弹出信息提示
Toast.makeText(InsertFlag.this, "〖新增便签〗数据添加成功!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(InsertFlag.this, "请输入便签!",
Toast.LENGTH_SHORT).show();
}
}
});
btnflagCancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
ShowInfo.java
ListView
显示便签列表,点击某一项跳转到 ManageFlag
活动package com.example.notemanagementsystem;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.notemanagementsystem.DAO.FlagDao;
import com.example.notemanagementsystem.model.flag;
import java.util.List;
public class ShowInfo extends Activity {
public static final String FLAG = "id";// 定义一个常量,用来作为请求码
ListView lvinfo;// 创建 ListView 对象
String[] strInfos = null;// 定义字符串数组,用来存储收入信息
ArrayAdapter<String> arrayAdapter = null;// 创建 ArrayAdapter 对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showinfo);
lvinfo = (ListView) findViewById(R.id.lvinfo);
FlagDao flaginfo = new FlagDao(ShowInfo.this);// 创建 FlagDAO 对象
// 获取所有便签信息,并存储到 List 泛型集合中
List<flag> listFlags = flaginfo.getScrollData(0,
(int) flaginfo.getCount());
strInfos = new String[listFlags.size()];// 设置字符串数组的长度
int n = 0;// 定义一个开始标识
for (flag tb_flag : listFlags) {
// 将便签相关信息组合成一个字符串,存储到字符串数组的相应位置
strInfos[n] = tb_flag.getid() + "|" + tb_flag.getFlag();
if (strInfos[n].length() > 15)// 判断便签信息的长度是否大于 15
strInfos[n] = strInfos[n].substring(0, 15) + "……";// 将位置大于 15之后的字符串用……代替
n++;// 标识加 1
}
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, strInfos);
lvinfo.setAdapter(arrayAdapter);
lvinfo.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String strInfo = String.valueOf(((TextView) view).getText());// 记录单击的项信息
String strid = strInfo.substring(0, strInfo.indexOf('|'));// 从项信息中截取编号
Intent intent = null;// 创建 Intent 对象
intent = new Intent(ShowInfo.this, ManageFlag.class);// 使用 FlagManage 窗口初始化 Intent 对象
intent.putExtra(FLAG, strid);// 设置要传递的数据
startActivity(intent);// 执行 Intent,打开相应的 Activity
}
});
}
}
ManageFlag.java
package com.example.notemanagementsystem;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.notemanagementsystem.DAO.FlagDao;
import com.example.notemanagementsystem.model.flag;
public class ManageFlag extends Activity {
EditText txtFlag;// 创建 EditText 对象
Button btnEdit, btnDel;// 创建两个 Button 对象
String strid;// 创建字符串,表示便签的 id
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manageflag);
txtFlag = (EditText) findViewById(R.id.txtFlagManage);
btnEdit = (Button) findViewById(R.id.btnFlagManageEdit);
btnDel = (Button) findViewById(R.id.btnFlagManageDelete);
Intent intent = getIntent();// 创建 Intent 对象
Bundle bundle = intent.getExtras();// 获取便签 id
strid = bundle.getString(ShowInfo.FLAG);// 将便签 id 转换为字符串
final FlagDao flagDAO = new FlagDao(ManageFlag.this);// 创建 FlagDAO 对象
txtFlag.setText(flagDAO.find(Integer.parseInt(strid)).getFlag());
// 为修改按钮设置监听事件
btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
flag tb_flag = new flag();// 创建 Tb_flag 对象
tb_flag.setid(Integer.parseInt(strid));// 设置便签 id
tb_flag.setFlag(txtFlag.getText().toString());// 设置便签值
flagDAO.update(tb_flag);// 修改便签信息
// 弹出信息提示
Toast.makeText(ManageFlag.this, "〖便签数据〗修改成功!",
Toast.LENGTH_SHORT).show();
}
});
// 为删除按钮设置监听事件
btnDel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
flagDAO.detele(Integer.parseInt(strid));// 根据指定的 id 删除便签信息
Toast.makeText(ManageFlag.this, "〖便签数据〗删除成功!",
Toast.LENGTH_SHORT).show();
}
});
}
}
DBOpenHelper.java
package com.example.notemanagementsystem.DAO;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBOpenHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;// 定义数据库版本号
private static final String DBNAME = "flag.db";// 定义数据库名
public DBOpenHelper(Context context) {
super(context, DBNAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) // 创建数据库
{
db.execSQL("create table tb_flag (_id integer primary key,flag varchar(200)) ");// 创建便签信息表
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) // 覆写基类的 onUpgrade方法,以便数据库版本更新
{
}
}
FlagDao.java
package com.example.notemanagementsystem.DAO;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.notemanagementsystem.DAO.DBOpenHelper;
import com.example.notemanagementsystem.model.flag;
public class FlagDao {
private DBOpenHelper helper;// 创建 DBOpenHelper 对象
private SQLiteDatabase db;// 创建 SQLiteDatabase 对象
public FlagDao(Context context)// 定义构造函数
{
helper = new DBOpenHelper(context);// 初始化 DBOpenHelper 对象
}
/**
* 添加便签信息
*
* @param tb_flag
*/
public void add(flag flag) {
db = helper.getWritableDatabase();// 初始化 SQLiteDatabase 对象
db.execSQL("insert into tb_flag (_id,flag) values (?,?)", new Object[]{
flag.getid(), flag.getFlag()});// 执行添加便签信息操作
}
/**
* 更新便签信息
*
* @param tb_flag
*/
public void update(flag tb_flag) {
db = helper.getWritableDatabase();// 初始化 SQLiteDatabase 对象
db.execSQL("update tb_flag set flag = ? where _id = ?", new Object[]{
tb_flag.getFlag(), tb_flag.getid()});// 执行修改便签信息操作
}
/**
* 查找便签信息
*
* @param id
* @return
*/
public flag find(int id) {
db = helper.getWritableDatabase();// 初始化 SQLiteDatabase 对象
Cursor cursor = db.rawQuery(
"select _id,flag from tb_flag where _id = ?",
new String[]{String.valueOf(id)});// 根据编号查找便签信息,并存储到 Cursor 类中
if (cursor.moveToNext())// 遍历查找到的便签信息
{
// 将遍历到的便签信息存储到 Tb_flag 类中
return new flag(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getString(cursor.getColumnIndex("flag")));
}
return null;// 如果没有信息,则返回 null
}
/**
* 刪除便签信息
*
* @param ids
*/
public void detele(Integer... ids) {
if (ids.length > 0)// 判断是否存在要删除的 id
{
StringBuffer sb = new StringBuffer();// 创建 StringBuffer 对象
for (int i = 0; i < ids.length; i++)// 遍历要删除的 id 集合
{
sb.append('?').append(',');// 将删除条件添加到 StringBuffer 对象中
}
sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符
db = helper.getWritableDatabase();// 创建 SQLiteDatabase 对象
// 执行删除便签信息操作
db.execSQL("delete from tb_flag where _id in (" + sb + ")",
(Object[]) ids);
}
}
/**
* 获取便签信息
*
* @param start 起始位置
* @param count 每页显示数量
* @return
*/
public List<flag> getScrollData(int start, int count) {
List<flag> lisTb_flags = new ArrayList<flag>();// 创建集合对象
db = helper.getWritableDatabase();// 初始化 SQLiteDatabase 对象
// 获取所有便签信息
Cursor cursor = db.rawQuery("select * from tb_flag limit ?,?",
new String[]{String.valueOf(start), String.valueOf(count)});
while (cursor.moveToNext())// 遍历所有的便签信息
{
// 将遍历到的便签信息添加到集合中
lisTb_flags.add(new flag(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getString(cursor.getColumnIndex("flag"))));
}
return lisTb_flags;// 返回集合
}
/**
* 获取总记录数
*
* @return
*/
public long getCount() {
db = helper.getWritableDatabase();// 初始化 SQLiteDatabase 对象
Cursor cursor = db.rawQuery("select count(_id) from tb_flag", null);// 获取便签信息的记录数
if (cursor.moveToNext())// 判断 Cursor 中是否有数据
{
return cursor.getLong(0);// 返回总记录数
}
return 0;// 如果没有数据,则返回 0
}
/**
* 获取便签最大编号
*
* @return
*/
public int getMaxId() {
db = helper.getWritableDatabase();// 初始化 SQLiteDatabase 对象
Cursor cursor = db.rawQuery("select max(_id) from tb_flag", null);// 获取便签信息表中的最大编号
while (cursor.moveToLast()) {// 访问 Cursor 中的最后一条数据
return cursor.getInt(0);// 获取访问到的数据,即最大编号
}
return 0;// 如果没有数据,则返回 0
}
}
flag.java
package com.example.notemanagementsystem.model;
public class flag {
private int _id;// 存储便签编号
private String flag;// 存储便签信息
public flag()// 默认构造函数
{
super();
}
// 定义有参构造函数,用来初始化便签信息实体类中的各个字段
public flag(int id, String flag) {
super();
this._id = id;// 为便签号赋值
this.flag = flag;// 为便签信息赋值
}
public int getid()// 设置便签编号的可读属性
{
return _id;
}
public void setid(int id)// 设置便签编号的可写属性
{
this._id = id;
}
public String getFlag()// 设置便签信息的可读属性
{
return flag;
}
public void setFlag(String flag)// 设置便签信息的可写属性
{
this.flag = flag;
}
}
AndroidManifest.xml
MainActivity
ShowInfo
, InsertFlag
, ManageFlag
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wenlong.DBLab.activity"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.example.notemanagementsystem.MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
<activity
android:name="com.example.notemanagementsystem.ShowInfo"
android:icon="@drawable/ic_launcher"
android:label="便签信息">activity>
<activity
android:name="com.example.notemanagementsystem.InsertFlag"
android:icon="@drawable/ic_launcher"
android:label="添加便签">activity>
<activity
android:name="com.example.notemanagementsystem.ManageFlag"
android:icon="@drawable/ic_launcher"
android:label="便签管理">activity>
application>
manifest>
1.文档结构
2.运行效果
在项目中创建一个用于管理数据库的帮助类。
package com.example.inventorymanagementsystem.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBOpenHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "inventory.db";
private static final int DB_VERSION = 1;
public DBOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建商品表
db.execSQL("CREATE TABLE IF NOT EXISTS products (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT," +
"quantity INTEGER," +
"price REAL)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 数据库升级操作
}
}
创建一个用于表示商品的实体类。
Product.java
package com.example.inventorymanagementsystem.model;
public class Product {
private int id;
private String name;
private int quantity;
private double price;
public Product() {
}
public Product(String name, int quantity, double price) {
this.name = name;
this.quantity = quantity;
this.price = price;
}
// Getter and setter methods
}
创建一个用于执行商品数据操作的类。
ProductDAO.java
package com.example.inventorymanagementsystem.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.inventorymanagementsystem.model.Product;
import java.util.ArrayList;
import java.util.List;
public class ProductDAO {
private SQLiteDatabase db;
public ProductDAO(Context context) {
DBOpenHelper dbHelper = new DBOpenHelper(context);
db = dbHelper.getWritableDatabase();
}
public long addProduct(Product product) {
ContentValues values = new ContentValues();
values.put("name", product.getName());
values.put("quantity", product.getQuantity());
values.put("price", product.getPrice());
return db.insert("products", null, values);
}
public List<Product> getAllProducts() {
List<Product> productList = new ArrayList<>();
Cursor cursor = db.query("products", null, null, null, null, null, null);
while (cursor.moveToNext()) {
Product product = new Product();
product.setId(cursor.getInt(cursor.getColumnIndex("_id")));
product.setName(cursor.getString(cursor.getColumnIndex("name")));
product.setQuantity(cursor.getInt(cursor.getColumnIndex("quantity")));
product.setPrice(cursor.getDouble(cursor.getColumnIndex("price")));
productList.add(product);
}
cursor.close();
return productList;
}
// 添加其他数据库操作方法,如更新商品信息、删除商品等
}
在 res/layout
文件夹中创建一个用于显示商品列表和添加商品的界面布局文件。
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="@+id/listViewProducts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@android:color/darker_gray"
android:dividerHeight="1dp" />
<Button
android:id="@+id/btnAddProduct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Product"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_margin="16dp"/>
RelativeLayout>
activity_add_product.xml
<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">
<EditText
android:id="@+id/edtProductName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="商品名称" />
<EditText
android:id="@+id/edtProductQuantity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="数量" />
<EditText
android:id="@+id/edtProductPrice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:hint="价格" />
<Button
android:id="@+id/btnAddProduct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加商品" />
LinearLayout>
MainActivity.java
package com.example.inventorymanagementsystem;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.inventorymanagementsystem.database.ProductDAO;
import com.example.inventorymanagementsystem.model.Product;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView listViewProducts;
private Button btnAddProduct;
private ProductDAO productDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listViewProducts = findViewById(R.id.listViewProducts);
btnAddProduct = findViewById(R.id.btnAddProduct);
productDAO = new ProductDAO(this);
updateProductList();
btnAddProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddProductActivity.class);
startActivity(intent);
}
});
}
private void updateProductList() {
List<Product> productList = productDAO.getAllProducts();
ArrayAdapter<Product> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, productList);
listViewProducts.setAdapter(adapter);
}
}
AddProductActivity.java
package com.example.inventorymanagementsystem;
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;
import com.example.inventorymanagementsystem.database.ProductDAO;
import com.example.inventorymanagementsystem.model.Product;
public class AddProductActivity extends AppCompatActivity {
private EditText edtProductName, edtProductQuantity, edtProductPrice;
private Button btnAddProduct;
private ProductDAO productDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
edtProductName = findViewById(R.id.edtProductName);
edtProductQuantity = findViewById(R.id.edtProductQuantity);
edtProductPrice = findViewById(R.id.edtProductPrice);
btnAddProduct = findViewById(R.id.btnAddProduct);
productDAO = new ProductDAO(this);
btnAddProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addProduct();
}
});
}
private void addProduct() {
// 获取用户输入的商品信息
String productName = edtProductName.getText().toString();
String quantityStr = edtProductQuantity.getText().toString();
String priceStr = edtProductPrice.getText().toString();
if (!productName.isEmpty() && !quantityStr.isEmpty() && !priceStr.isEmpty()) {
int quantity = Integer.parseInt(quantityStr);
double price = Double.parseDouble(priceStr);
// 创建商品对象
Product newProduct = new Product(productName, quantity, price);
// 将商品添加到数据库
long result = productDAO.addProduct(newProduct);
if (result != -1) {
Toast.makeText(AddProductActivity.this, "商品添加成功", Toast.LENGTH_SHORT).show();
finish(); // 关闭当前界面
} else {
Toast.makeText(AddProductActivity.this, "商品添加失败", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(AddProductActivity.this, "请填写完整的商品信息", Toast.LENGTH_SHORT).show();
}
}
}