SQLite 和 SQLiteDatabase 的使用

實驗七:SQLite 和 SQLiteDatabase 的使用

7.1 實驗目的

本次實驗的目的是讓大家熟悉 Android 中對數據庫進行操作的相關的接口、類等。SQLiteDatabase 這個是在 android 中數據庫操作使用最頻繁的一個類。通過它可以實現數據庫的創建或打開、創建表、插入數據、刪除數據、查詢數據、修改數據等操作。

7.2 實驗要求

  • 實現便簽管理小例程。
  • 創建項目并熟悉文件目錄結構
  • 實現便簽增刪改查功能的實驗步驟

7.3 實驗內容

【練習 7.1】 便簽管理小例程
步驟 1: 項目結構

創建一個名為"便簽管理系統"的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 (清單文件)
步驟 2: 配置布局文件
  1. 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"><LinearLayoutandroid:id="@+id/linearLayout1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="0.06"android:orientation="vertical"><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"><Buttonandroid:id="@+id/btnflaginfo"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="便簽信息"android:textColor="#8C6931"android:textSize="20dp" /><Buttonandroid: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>
      
  2. Insertinfo.xml (新增便簽窗體)

    • 包含一個文本框 txtFlag 用于輸入便簽內容

    • 包含兩個按鈕:btnflagSave (保存) 和 btnflagCancel (取消)

      <?xml version="1.0" encoding="utf-8"?>
      <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"><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_weight="3"android:orientation="vertical"><TextViewandroid: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><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_weight="1"android:orientation="vertical"><RelativeLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:padding="5dp"><TextViewandroid: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" /><EditTextandroid:id="@+id/txtFlag"android:layout_width="350dp"android:layout_height="400dp"android:layout_below="@id/tvFlag"android:gravity="top"android:singleLine="false" /></RelativeLayout></LinearLayout><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_weight="3"android:orientation="vertical"><RelativeLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:padding="10dp"><Buttonandroid:id="@+id/btnflagCancel"android:layout_width="80dp"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_marginLeft="10dp"android:text="取消" /><Buttonandroid: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>
      
  3. showinfo.xml (查看便簽信息窗體)

    • 包含一個文本視圖 textView1 和一個列表視圖 lvinfo 用于展示便簽信息
    <?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"><TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="便簽信息"android:textSize="20dp" /><LinearLayoutandroid:id="@+id/linearLayout2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="0.94"android:orientation="vertical"><ListViewandroid:id="@+id/lvinfo"android:layout_width="match_parent"android:layout_height="match_parent"android:scrollbarAlwaysDrawVerticalTrack="true" /></LinearLayout>
    </LinearLayout>
    
  4. manageflag.xml (便簽管理窗體)

    • 包含一個文本框 txtFlagManage 和兩個按鈕:btnFlagManageEdit (修改) 和 btnFlagManageDelete (刪除)
    <?xml version="1.0" encoding="utf-8"?>
    <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"><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_weight="3"android:orientation="vertical"><TextViewandroid: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><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_weight="1"android:orientation="vertical"><RelativeLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:padding="5dp"><TextViewandroid: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" /><EditTextandroid:id="@+id/txtFlagManage"android:layout_width="350dp"android:layout_height="400dp"android:layout_below="@id/tvFlagManage"android:gravity="top"android:singleLine="false" /></RelativeLayout></LinearLayout><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_weight="3"android:orientation="vertical"><RelativeLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:padding="10dp"><Buttonandroid:id="@+id/btnFlagManageDelete"android:layout_width="80dp"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_marginLeft="10dp"android:text="刪除" /><Buttonandroid: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>
    
步驟 3: 配置活動文件
  1. MainActivity.java

    • 初始化界面和按鈕
    • 為按鈕添加點擊事件,分別跳轉到 ShowInfoInsertFlag 活動
    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;@Overrideprotected 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() {@Overridepublic void onClick(View v) {Intent intent = new Intent(MainActivity.this, ShowInfo.class);startActivity(intent);}});btninsertinfo.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent(MainActivity.this, InsertFlag.class);startActivity(intent);}});}@Overridepublic 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;}
    }
    
  2. 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 組件對象@Overrideprotected 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() {@Overridepublic 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() {@Overridepublic void onClick(View v) {finish();}});}
    }
    
  3. 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 對象@Overrideprotected 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)// 判斷便簽信息的長度是否大于 15strInfos[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() {@Overridepublic 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}});}
    }
    
  4. ManageFlag.java

    • 處理便簽管理的界面邏輯
    • 獲取傳遞的便簽id,顯示該便簽內容,可進行編輯和刪除操作
    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@Overrideprotected 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();// 獲取便簽 idstrid = 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() {@Overridepublic void onClick(View v) {flag tb_flag = new flag();// 創建 Tb_flag 對象tb_flag.setid(Integer.parseInt(strid));// 設置便簽 idtb_flag.setFlag(txtFlag.getText().toString());// 設置便簽值flagDAO.update(tb_flag);// 修改便簽信息// 彈出信息提示Toast.makeText(ManageFlag.this, "〖便簽數據〗修改成功!",Toast.LENGTH_SHORT).show();}});// 為刪除按鈕設置監聽事件btnDel.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {flagDAO.detele(Integer.parseInt(strid));// 根據指定的 id 刪除便簽信息Toast.makeText(ManageFlag.this, "〖便簽數據〗刪除成功!",Toast.LENGTH_SHORT).show();}});}
    }
    
步驟 4: 配置數據庫相關文件
  1. 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);}@Overridepublic void onCreate(SQLiteDatabase db) // 創建數據庫{db.execSQL("create table tb_flag (_id integer primary key,flag varchar(200)) ");// 創建便簽信息表}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) // 覆寫基類的 onUpgrade方法,以便數據庫版本更新{}
    }
    
  2. 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}
    }
    
  3. 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;}
    }
    
步驟 5: 配置清單文件
  1. AndroidManifest.xml

    • 配置主活動為 MainActivity
    • 配置其他三個活動: ShowInfo, InsertFlag, ManageFlag
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.wenlong.DBLab.activity"android:versionCode="1"android:versionName="1.0"><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="18" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme"><activityandroid: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><activityandroid:name="com.example.notemanagementsystem.ShowInfo"android:icon="@drawable/ic_launcher"android:label="便簽信息"></activity><activityandroid:name="com.example.notemanagementsystem.InsertFlag"android:icon="@drawable/ic_launcher"android:label="添加便簽"></activity><activityandroid:name="com.example.notemanagementsystem.ManageFlag"android:icon="@drawable/ic_launcher"android:label="便簽管理"></activity></application>
    </manifest>
    
步驟 6: 運行與測試

1.文檔結構

image-20231124152548336

2.運行效果

image-20231124152727243

image-20231124152751315

【拓展題】編寫 Android 項目,實現商品庫存數據庫管理小系統。
步驟一:創建新的 Android 項目
  1. 打開 Android Studio。
  2. 選擇 “File” -> “New” -> “New Project…”。
  3. 在彈出的對話框中,輸入項目名稱為 “InventoryManagementSystem”,選擇語言為 Java,選擇 “Phone and Tablet” -> “Empty Activity”,然后點擊 “Finish”。
步驟二:創建數據庫幫助類(DBOpenHelper)

在項目中創建一個用于管理數據庫的幫助類。

DBOpenHelper.java
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);}@Overridepublic void onCreate(SQLiteDatabase db) {// 創建商品表db.execSQL("CREATE TABLE IF NOT EXISTS products (" +"_id INTEGER PRIMARY KEY AUTOINCREMENT," +"name TEXT," +"quantity INTEGER," +"price REAL)");}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// 數據庫升級操作}
}
步驟三:創建商品實體類(Product)

創建一個用于表示商品的實體類。

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)

創建一個用于執行商品數據操作的類。

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;}// 添加其他數據庫操作方法,如更新商品信息、刪除商品等
}
步驟五:創建商品管理界面(MainActivity)

res/layout 文件夾中創建一個用于顯示商品列表和添加商品的界面布局文件。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"><ListViewandroid:id="@+id/listViewProducts"android:layout_width="match_parent"android:layout_height="match_parent"android:divider="@android:color/darker_gray"android:dividerHeight="1dp" /><Buttonandroid: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"><EditTextandroid:id="@+id/edtProductName"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="商品名稱" /><EditTextandroid:id="@+id/edtProductQuantity"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="number"android:hint="數量" /><EditTextandroid:id="@+id/edtProductPrice"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="numberDecimal"android:hint="價格" /><Buttonandroid: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;@Overrideprotected 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() {@Overridepublic 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;@Overrideprotected 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() {@Overridepublic 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();}}
}
步驟六:運行效果

image-20231124162406148

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/167973.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/167973.shtml
英文地址,請注明出處:http://en.pswp.cn/news/167973.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

22、什么是中間件和權限攔截中間件實操

新建中間件 middleware\auth.js // 定義權限判斷中間件&#xff0c;中間件的第一個參數是context export default ({store, redirect}) > {console.log("中間件被調用")// if (!store || !store.state.userinfo) {// redirect("/")// } }頁面使用…

CF -- Educational Codeforces Round 158 (Rated for Div. 2) -- D 補題記錄

Yet Another Monster Fight Problem - D - Codeforces 題目大意&#xff1a; 現在給你一堆怪物&#xff0c;你擁有法術&#xff08;一個法術可以連續攻擊這n個所有怪物&#xff09;&#xff0c;你可以選擇任意一個怪物作為法術的第一個攻擊目標&#xff08;傷害為x&#xff…

【MySQL】索引與事務

&#x1f451;專欄內容&#xff1a;MySQL?個人主頁&#xff1a;子夜的星的主頁&#x1f495;座右銘&#xff1a;前路未遠&#xff0c;步履不停 目錄 一、索引1、使用場景2、使用索引創建索引查看索引刪除索引 3、底層數據結構&#xff08;非常重要&#xff09; 二、事務1、概念…

Android設計模式--享元模式

水不激不躍&#xff0c;人不激不奮 一&#xff0c;定義 使用共享對象可有效地支持大量的細粒度的對象 享元模式是對象池的一種實現&#xff0c;用來盡可能減少內存使用量&#xff0c;它適合用于可能存在大量重復對象的場景&#xff0c;來緩存可共享的對象&#xff0c;達到對象…

騰訊云CVM標準型SA5云服務器AMD EPYC Bergamo處理器

騰訊云服務器標準型SA5實例是最新一代的標準型實例&#xff0c;CPU采用AMD EPYC? Bergamo全新處理器&#xff0c;采用最新DDR5內存&#xff0c;默認網絡優化&#xff0c;最高內網收發能力達4500萬pps。騰訊云百科txybk.com分享騰訊云標準型SA5云服務器CPU、內存、網絡、性能、…

Qt項目打包發布超詳細教程

https://blog.csdn.net/qq_45491628/article/details/129091320

用蘋果簽名免費獲取Xcode

使用蘋果企業簽名免費獲取Xcode&#xff1a; 打開Xcode。連接iOS設備到Mac。選擇Window→Devices and Simulators。選擇該設備。將IPA文件拖到“Installed Apps”的列表框中即可安裝。使用Cydia Impactor&#xff08;可以在網上找到相關下載鏈接&#xff09;&#xff1a; 打開…

HTML網站穩定性狀態監控平臺源碼

這是一款網站穩定性狀態監控平臺源碼&#xff0c;它基于UptimeRobot接口進行開發。當您的網站遇到故障時&#xff0c;該平臺能夠通過郵件或短信通知您。下面是對安裝過程的詳細說明&#xff1a; 安裝步驟 將源碼上傳至您的主機或服務器&#xff0c;并進行解壓操作。 在Uptim…

自動化測試中幾種常見驗證碼的處理方式及如何實現?

UI自動化測試時&#xff0c;需要對驗證碼進行識別處理&#xff0c;有很多方式&#xff0c;每種方式都有自己的特點&#xff0c;以下是一些常用處理方法&#xff0c;僅供參考。 1 去掉驗證碼 從自動化的本質上來講&#xff0c;主要是提升測試效率等&#xff0c;但是為了去研究驗…

【點云surface】 修剪B樣條曲線擬合

1 介紹 Fitting trimmed B-splines&#xff08;修剪B樣條曲線擬合&#xff09;是一種用于對給定的點云數據進行曲線擬合的算法。該算法使用B樣條曲線模型來逼近給定的點云數據&#xff0c;并通過對模型進行修剪來提高擬合的精度和準確性。 B樣條曲線是一種常用的曲線表示方法…

【element優化經驗】el-dialog修改title樣式

目錄 前言 解決之路 1.把默認的這個圖標隱藏&#xff0c;官方的api有這個屬性&#xff1a;showClose值設置false. 2.title插槽定制&#xff1a;左邊定制標題&#xff0c;右邊定制按鈕區域。 3.背景顏色修改&#xff1a;默認title是有padding的需要把它重寫調&#xff0c;然…

基于卷積神經網絡CNN開發構建HAR人類行為識別Human Activity Recognition【完整代碼實踐】

行為識別相關的開發實踐在我們之前的博文中也有過相關的實踐了,感興趣的話可以自行移步閱讀即可:《python實現基于TNDADATASET的人體行為識別》 《UCI行為識別——Activity recognition with healthy older people using a batteryless wearable sensor Data Set》《人體行為…

基于 STM32Cube.AI 的嵌入式人臉識別算法實現

本文介紹了如何使用 STM32Cube.AI 工具開發嵌入式人臉識別算法。首先&#xff0c;我們將簡要介紹 STM32Cube.AI 工具和 STM32F系列單片機的特點。接下來&#xff0c;我們將詳細討論如何使用 STM32Cube.AI 工具鏈和相關庫來進行人臉識別算法的開發和優化。最后&#xff0c;我們提…

Netty實現websocket且實現url傳參的兩種方式(源碼分析)

1、先構建基本的netty框架 再下面的代碼中我構建了一個最基本的netty實現websocket的框架&#xff0c;其他個性化部分再自行添加。 Slf4j public class TeacherServer {public void teacherStart(int port) throws InterruptedException {NioEventLoopGroup boss new NioEve…

Day40力扣打卡

打卡記錄 包子湊數&#xff08;裴蜀定理 DP&#xff09; 根據裴蜀定理&#xff0c;存在 c gcd(a, b) 使不定方程ax by c滿足條件&#xff0c;如果gcd(a, b) 1即a與b互素的情況下&#xff0c;就會 ax by 1&#xff0c;由于為1可以構造后面的無窮數字&#xff0c;故得到結…

Centos7 離線安裝 CDH7.1.7

1. 安裝CDH的準備工作&#xff08;所有節點都要執行&#xff09; 1.1 準備環境 角色 IP k8s-master 192.168.181.129 k8s-node1 192.168.181.130 k8s-node2 192.168.181.131 1.2 安裝JDK # https://www.oracle.com/java/technologies/downloads/#java11 wget rpm -ivh…

亞馬遜Listing怎么寫!親身經驗分享

亞馬遜運營的重要環節之一&#xff0c;listing的攥寫&#xff0c;可以決定了產品的搜索排名&#xff0c;用戶的點擊率和轉化率&#xff0c;那么如果你的產品排名或者轉化不理想的情況&#xff0c;可以考慮對listing進行優化&#xff0c;在關鍵詞過多和語句流程通順的情況下&…

js獲取時間日期

目錄 Date 對象 1. 獲取當前時間 2. 獲取特定日期時間 Date 對象的方法 1. 獲取各種日期時間組件 2. 獲取星期幾 3. 獲取時間戳 格式化日期時間 1. 使用 toLocaleString() 方法 2. 使用第三方庫 UNIX 時間戳 內部表示 時區 Date 對象 JavaScript中內置的 Date 對象…

數據挖掘之PCA-主成分分析

PCA的用處&#xff1a;找出反應數據中最大變差的投影&#xff08;就是拉的最開&#xff09;。 在減少需要分析的指標同時&#xff0c;盡量減少原指標包含信息的損失&#xff0c;以達到對所收集數據進行全面分析的目的 但是什么時候信息保留的最多呢&#xff1f;具體一點&#…

?飛凌嵌入式FCU2601網關,為工商業儲能EMS注入智慧的力量

一、火熱的儲能行業&#xff0c;尋求新的市場機會 最近一段時間以來&#xff0c;世界儲能大會、上海儲能展、能源電子產業發展大會等多個儲能相關論壇和展覽密集登場&#xff0c;即使“內卷”已成為了業內討論的熱詞&#xff0c;但尋求新的市場機會仍然是行業共識&#xff0c;…