XML界面設計??
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="姓名:" /><EditTextandroid:id="@+id/etc_name"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="50px" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="班級:" /><EditTextandroid:id="@+id/etc_class"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="50px" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="學號:" /><EditTextandroid:id="@+id/etc_id"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="50px" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:id="@+id/btn_add"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="添加數據"android:textAlignment="center" /><Buttonandroid:id="@+id/btn_show"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="全部顯示"android:textAlignment="center" /><Buttonandroid:id="@+id/btn_clr"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="清除數據"android:textAlignment="center" /><Buttonandroid:id="@+id/btn_del"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="全部刪除"android:textAlignment="center" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="ID:" /><EditTextandroid:id="@+id/etc_id2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="2" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:id="@+id/btn_del_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="ID刪除"android:textAlignment="center" /><Buttonandroid:id="@+id/btn_show_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="ID查詢"android:textAlignment="center" /><Buttonandroid:id="@+id/btn_update_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="ID更新"android:textAlignment="center" /></LinearLayout><TextViewandroid:id="@+id/txt_end"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="" /><ListViewandroid:id="@+id/list"android:layout_width="match_parent"android:layout_height="wrap_content"/></LinearLayout>
People.java
package com.example.exp6;public class People {public int ID = -1;public String Name;public String Class;public String Number;//重載toString方法 返回值String類型@Overridepublic String toString(){String result = "";result += "ID:" + this.ID + ",";result += "姓名:" + this.Name + ",";result += "班級:" + this.Class + ", ";result += "學號:" + this.Number;return result;}
}
?DBAdapter.java
package com.example.exp6;
import android.annotation.SuppressLint;
import android.content.*;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;import androidx.annotation.Nullable;//對數據庫進行操作的類
public class DBAdapter {private static final String DB_NAME = "student.db"; //數據庫名稱private static final String DB_TABLE = "peopleinfo"; //表名private static final int DB_VERSION = 1; //數據庫版本public static final String KEY_ID = "_id"; //數據庫表的屬性名稱public static final String KEY_NAME = "name";public static final String KEY_CLASS = "class";public static final String KEY_NUMBER = "number";private SQLiteDatabase db; //數據庫的實例dbprivate final Context context; //Context的實例化private DBOpenHelper dbOpenHelper; //幫助類的實例化 dbOpenHelper//內部類:對幫助類 構建//繼承SQLiteOpenHelper//必須重載onCreate和onUpgrade方法private static class DBOpenHelper extends SQLiteOpenHelper {//幫助類的構造函數 -- 4個參數//Code -> SQLiteOpenHelper 即可成功插入該構造函數public DBOpenHelper(@Nullable Context context, @Nullable String name,SQLiteDatabase.CursorFactory factory, int version) {super(context, name, factory, version);}//static常量字符串--創建表的 sql 命令//create table peopleinfo("id integer primary key autoincrement,name text not null,// class text not null,number text not null")private static final String DB_CREATE = "create table " +DB_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " +KEY_NAME + " text not null, " + KEY_CLASS + " text not null," +KEY_NUMBER + " text not null);";//重載幫助類onCreate方法//1個參數SQLiteDatabase類型@Overridepublic void onCreate(SQLiteDatabase sqLiteDatabase) {//execSQL()方法 1個String類型的 sql 建表命令sqLiteDatabase.execSQL(DB_CREATE);}//重載幫助類onUpdate方法//一般在升級的時候被調用//刪除舊的數據庫表 并將數據轉移到新版本的數據庫表//3個參數SQLiteDatabase類型、int i-舊版本號、int i1-新版本號@Overridepublic void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {//僅刪除原表后建立新表sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);onCreate(sqLiteDatabase);}}//對數據庫進行操作的類DBAdapter的構造//參數1個 Context類型public DBAdapter(Context _context) {context = _context;}//DBAdapter類的open方法//拋出異常!!!!public void open() throws SQLiteException {//幫助類實例化dbOpenHelper需要4個參數dbOpenHelper = new DBOpenHelper(context, DB_NAME,null, DB_VERSION);//調用getWritableDatabase方法try {db = dbOpenHelper.getWritableDatabase();} catch (SQLiteException ex) {db = dbOpenHelper.getReadableDatabase();}}//DBAdapter類的close方法public void close() {if (db != null) {db.close();db = null;}}//DBAdapter類的insert方法//參數1個:數據庫儲存的類型(本例是Peoplepublic long insert(People people) {//用ContentValues類型ContentValues newValues = new ContentValues();//在put的時候不需要put Key_ID!!!newValues.put(KEY_NAME, people.Name);newValues.put(KEY_CLASS, people.Class);newValues.put(KEY_NUMBER, people.Number);//返回值是新數據插入的位置 ID值//數據庫對象.insert方法//參數3個:表名 在null時的替換數據 ContentValues類型需要添加的數據return db.insert(DB_TABLE, null, newValues);}//DBAdapter類的deleteAllData方法//無參數public long deleteAllData() {//返回值是被刪除的數據的數量//參數3個:表名 刪除條件(刪除全部數據條件是null)return db.delete(DB_TABLE, null, null);}//DBAdapter類的deleteOneData方法//參數1個:long類型的id值public long deleteOneData(long id) {//返回值是被刪除的數據的數量//參數3個:表名 刪除條件(刪除形參給的id)return db.delete(DB_TABLE, KEY_ID + "=" + id, null);}//DBAdapter類的UpdataOneData方法//參數2個:long類型的id值 和 People類型public long updateOneData(long id , People people){//更新和插入一樣用到了ContentValues類型ContentValues updateValues = new ContentValues();//同樣不需要放Key_IDupdateValues.put(KEY_NAME, people.Name);updateValues.put(KEY_CLASS, people.Class);updateValues.put(KEY_NUMBER, people.Number);//返回值是被更新的數據數量//參數4個 表明 ContentValues 更新條件string類型 nullreturn db.update(DB_TABLE, updateValues, KEY_ID + "=" + id, null);}//private類型//DBAdapter類的ConvertToPeople方法//參數1個 Cursor類型//返回People數組//查詢需要基于該 ConvertToPeople 方法(應該是自定義方法?)@SuppressLint("Range")private People[] ConvertToPeople(Cursor cursor){//getCount方法返回查詢結果總行數int resultCounts = cursor.getCount();//行數為0||moveToFirst方法返回false返回結果為空if (resultCounts == 0 || !cursor.moveToFirst()){//該方法返回nullreturn null;}//新建resultCounts個People對象People[] peoples = new People[resultCounts];//循環 resultCounts次for (int i = 0 ; i<resultCounts; i++){peoples[i] = new People();peoples[i].ID = cursor.getInt(0);//根據 列屬性索引 得到 屬性值peoples[i].Name = cursor.getString(cursor.getColumnIndex(KEY_NAME));peoples[i].Class = cursor.getString(cursor.getColumnIndex(KEY_CLASS));peoples[i].Number = cursor.getString(cursor.getColumnIndex(KEY_NUMBER));//游標/指針下移cursor.moveToNext();}//返回People[]return peoples;}//查詢操作://DBAdapter類的getOneData方法//參數1個:long類型的id值public People[] getOneData(long id) {//query方法//參數7個(6String 1String[]):表名稱 屬性列-String[] 查詢條件//查詢條件是否使用通配符 分組條件 分組過濾條件 排序方式 后4個全是null//返回Cursor類型Cursor results = db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_CLASS, KEY_NUMBER},KEY_ID + "=" + id, null, null, null, null);//返回People[]return ConvertToPeople(results);}//DBAdapter類的getAllData方法public People[] getAllData() {//參數查詢條件為null 存在5個nullCursor results = db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_CLASS, KEY_NUMBER},null, null, null, null, null);return ConvertToPeople(results);}}
MainActivity.java?
package com.example.exp6;import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
import android.widget.ArrayAdapter;public class MainActivity extends AppCompatActivity {EditText etc_name,etc_class,etc_id,etc_id2;TextView txt_end;ListView listView;Button btn_add,btn_show,btn_clr,btn_del,btn_del_id,btn_show_id,btn_update_id;DBAdapter dbAdapter;SQLiteDatabase db;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listView=findViewById(R.id.list);ArrayList<String> data=new ArrayList<String>();//數組適配器//實例化 參數3個ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);etc_name=findViewById(R.id.etc_name);etc_class=findViewById(R.id.etc_class);etc_id=findViewById(R.id.etc_id);btn_add=findViewById(R.id.btn_add);btn_show=findViewById(R.id.btn_show);btn_clr=findViewById(R.id.btn_clr);btn_del=findViewById(R.id.btn_del);btn_del_id=findViewById(R.id.btn_del_id);btn_show_id=findViewById(R.id.btn_show_id);btn_update_id= findViewById(R.id.btn_update_id);etc_id2=findViewById(R.id.etc_id2);txt_end=findViewById(R.id.txt_end);//處理數據庫的類的實例對象//參數1個 Context類型dbAdapter=new DBAdapter(this);//調用DBAdapter對象的 open 方法dbAdapter.open();btn_add.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//將文本框中的內容用來創建對象PeoplePeople t=new People();t.Name=etc_name.getText().toString();t.Class=etc_class.getText().toString();t.Number=etc_id.getText().toString();//插入一個對象People//返回插入的位置idlong colunm=dbAdapter.insert(t);if (colunm == -1 ){txt_end.setText("添加過程錯誤!");} else {txt_end.setText("ID:"+String.valueOf(colunm)+" 姓名:"+t.Name+" 班級:"+t.Class+" 學號:"+t.Number);}}});btn_show.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//調用得到數據庫中全部的信息People [] peoples =dbAdapter.getAllData();if (peoples == null){txt_end.setText("數據庫中沒有數據");return;}String t="數據庫:\n";for(int i=0;i<peoples.length;++i){t += peoples[i].toString()+"\n";}txt_end.setText(t);}});btn_clr.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {txt_end.setText("");}});btn_del.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {dbAdapter.deleteAllData();txt_end.setText("已刪除所有數據!");}});btn_del_id.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {int id=Integer.parseInt(etc_id2.getText().toString());//返回刪除的數據的數量//參數要求int類型的long result=dbAdapter.deleteOneData(id);String msg = "刪除ID為"+etc_id2.getText().toString()+"的數據" + (result>0?"成功":"失敗");txt_end.setText(msg);}});btn_show_id.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {int id=Integer.parseInt(etc_id2.getText().toString());//查找方法 參數id-int//返回值是People[]People people[]=dbAdapter.getOneData(id);if(people==null){txt_end.setText("Id為"+id+"的記錄不存在!");}else{//因為僅只查找了一條信息 所以是people[0]//并且在People類型中已經重載了函數toString()txt_end.setText("查詢成功:\n"+people[0].toString());}}});btn_update_id.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {int id=Integer.parseInt(etc_id2.getText().toString());People t=new People();t.Name=etc_name.getText().toString();t.Class=etc_class.getText().toString();t.Number=etc_id.getText().toString();//更新方法//參數2個 id-int people類型//返回值 被更新的數據數量long n=dbAdapter.updateOneData(id,t);if (n<0){txt_end.setText("更新過程錯誤!");}else{txt_end.setText("成功更新數據,"+String.valueOf(n)+"條");}}});}@Overrideprotected void onStop() {super.onStop();dbAdapter.close();}
}
結果
數據添加(朱迪&尼克狐尼克)
全部顯示?
ID刪除 (25-朱迪)
?ID查詢 (26)
ID更新 (26)?
全部刪除
全部顯示?