Android[中級教程]第三章 資料存放區之SQLite

來源:互聯網
上載者:User

 這一章我們來學習Android資料庫SQLite,還是接上一章的,對於唐僧師徙去西天,三個徙弟得要殺妖怪啊,那得有個匯總啊,有個記數啊,這裡我們就用SQLite來儲存各徙弟殺死妖怪的數量,OK,上main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:layout_height="match_parent"><TextView android:layout_height="wrap_content"android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="西遊記各主人公殺死妖怪數"android:id="@+id/textView1"></TextView><Button android:text="增加一個主角" android:id="@+id/add_btn"android:layout_width="wrap_content" android:layout_height="wrap_content"></Button><Button android:text="更新主角殺死妖怪數" android:id="@+id/update_btn"android:layout_width="wrap_content" android:layout_height="wrap_content"></Button><Button android:text="刪除一個主角" android:id="@+id/del_btn"android:layout_width="wrap_content" android:layout_height="wrap_content"></Button><ListView android:layout_height="wrap_content" android:id="@+id/listView1"android:layout_width="match_parent"></ListView></LinearLayout>

這裡定義了三個按鈕,一個ListView,接下來又定義了三個Layout,分別顯示"增加一個主角","更新主角殺死妖怪數","刪除一個主角"的頁面,分別如下:

add_item.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:layout_height="match_parent" android:padding="10dp"><TextView android:layout_height="wrap_content"android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="主角名稱"></TextView><EditText android:layout_height="wrap_content"android:layout_width="match_parent" android:id="@+id/add_name"><requestFocus></requestFocus></EditText><TextView android:layout_height="wrap_content"android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="殺死妖怪數量"></TextView><EditText android:layout_height="wrap_content"android:layout_width="match_parent" android:id="@+id/add_number"android:inputType="number"></EditText></LinearLayout>

update_item.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:layout_height="match_parent" android:padding="10dp"><TextView android:layout_height="wrap_content"android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="ID"></TextView><EditText android:layout_height="wrap_content"android:layout_width="match_parent" android:id="@+id/update_id"android:inputType="number"><requestFocus></requestFocus></EditText><TextView android:layout_height="wrap_content"android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="殺死妖怪數量"></TextView><EditText android:layout_height="wrap_content"android:layout_width="match_parent" android:id="@+id/update_number"android:inputType="number"></EditText></LinearLayout>

delete_item.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:layout_height="match_parent" android:padding="10dp"><TextView android:layout_height="wrap_content"android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="ID"></TextView><EditText android:layout_height="wrap_content"android:layout_width="match_parent" android:id="@+id/delete_id"android:inputType="number"><requestFocus></requestFocus></EditText></LinearLayout>

最後再定義一個List_item.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:layout_height="match_parent"><LinearLayout android:layout_height="wrap_content"android:id="@+id/linearLayout1" android:layout_width="match_parent"><TextView android:layout_height="wrap_content"android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="ID: "android:paddingLeft="10dp"></TextView><TextView android:layout_height="wrap_content"android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="TextView"android:id="@+id/id"></TextView><TextView android:layout_height="wrap_content"android:textAppearance="?android:attr/textAppearanceMedium"android:layout_width="wrap_content" android:text="TextView"android:id="@+id/name" android:paddingLeft="30dp"></TextView></LinearLayout><LinearLayout android:layout_height="wrap_content"android:id="@+id/linearLayout2" android:layout_width="match_parent"><TextView android:layout_height="wrap_content"android:layout_width="wrap_content" android:text="殺死了"android:paddingLeft="10dp"></TextView><TextView android:text="TextView" android:id="@+id/number"android:layout_width="wrap_content" android:layout_height="wrap_content"android:textColor="#FF0000"></TextView><TextView android:text="只妖怪" android:layout_width="wrap_content"android:layout_height="wrap_content"></TextView></LinearLayout></LinearLayout>

OK,定義完了,,我們就來建立資料庫了,建立一個DatabaseHelper.java

import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class DatabaseHelper extends SQLiteOpenHelper{//資料庫名稱private static final String DB_NAME = "SQLiteDemo.db";//資料庫版本private static final int DB_VERSION = 1;//表名public static final String TABLE_NAME = "demo";private static final String DB_CREATE = "create table " + TABLE_NAME +  " (_id integer primary key autoincrement, name varchar(20), number varchar(10))";public DatabaseHelper(Context context){super(context, DB_NAME, null, DB_VERSION);}/** * 建立表 */@Overridepublic void onCreate(SQLiteDatabase db){db.execSQL(DB_CREATE);}/** * 更新表 */@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){//db.execSQL("drop table if exists " + TABLE_NAME);//onCreate(db);}}

另外再建立一個資料庫操作輔助類DatabaseServer.java

import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;public class DatabaseServer{private DatabaseHelper dbHelper;public DatabaseServer(Context context){this.dbHelper = new DatabaseHelper(context);}/** * 插入資料 *  * @param name *            名字 * @param number *            資料 * @return 如果成功則返回true,否則返回false */public boolean insert(String name, String number){//建立或開啟資料庫SQLiteDatabase db = dbHelper.getWritableDatabase();ContentValues cv = new ContentValues();cv.put("name", name);cv.put("number", number);//插入資料,返回插入資料IDlong id = db.insert(dbHelper.TABLE_NAME, null, cv);if (id != 0){return true;}return false;}/** * 更新資料 *  * @param id *            資料列_id * @param number *            數量 * @return 如果成功則返回true,否則返回false */public boolean update(int id, String number){SQLiteDatabase db = dbHelper.getWritableDatabase();//Android內建的ContetValues,類似於Map,提供了put(String key, XXX value)的方法存入資料ContentValues cv = new ContentValues();cv.put("number", number);//通過ContentValues更新資料表,返回更新的ID值int result = db.update(dbHelper.TABLE_NAME, cv, "_id=?",new String[] { String.valueOf(id) });if (result != 0){return true;}return false;}/** * 刪除資料 *  * @param id *            資料列_id * @return */public boolean delete(int id){SQLiteDatabase db = dbHelper.getWritableDatabase();//刪除指定ID值int result = db.delete(dbHelper.TABLE_NAME, "_id=?",new String[] { String.valueOf(id) });if (result != 0){return true;}return false;}/** * 查詢資料 *  * @return 返回資料列表 */public Cursor fetchAll(){SQLiteDatabase db = dbHelper.getReadableDatabase();//查詢資料表中所有欄位Cursor cursor = db.query(dbHelper.TABLE_NAME, null, null, null, null,null, "_id desc");if (cursor != null){return cursor;}return null;}}

這裡將插入,更新,刪除,查詢分別做了簡單的封裝,OK,最後就是Activity類了

import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.database.Cursor;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import android.widget.SimpleCursorAdapter;import android.widget.Toast;public class SQLiteDemo extends Activity implements OnClickListener{private Button add_btn;private Button update_btn;private Button del_btn;private ListView listView;private DatabaseServer dbServer;@Overrideprotected void onCreate(Bundle savedInstanceState){// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.sqlite);add_btn = (Button) findViewById(R.id.add_btn);add_btn.setOnClickListener(this);update_btn = (Button) findViewById(R.id.update_btn);update_btn.setOnClickListener(this);del_btn = (Button) findViewById(R.id.del_btn);del_btn.setOnClickListener(this);listView = (ListView) findViewById(R.id.listView1);dbServer = new DatabaseServer(this);//自訂方法SetInAdapter();}/** * 將資料庫裡查詢到的資料匹配進ListView中 */private void SetInAdapter(){Cursor cursor = dbServer.fetchAll();SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.list_item, cursor, new String[] { "_id", "name","number" },new int[] { R.id.id, R.id.name, R.id.number });listView.setAdapter(adapter);}@Overridepublic void onClick(View v){switch (v.getId()){case R.id.add_btn://資料插入data_add();break;case R.id.update_btn://資料更新data_update();break;case R.id.del_btn://資料刪除data_delete();break;}}/** * 刪除主角 */private void data_delete(){//通過擴充,將delete_item.xml放入視圖中final View delete_view = LayoutInflater.from(this).inflate(R.layout.delete_item, null);AlertDialog.Builder dialog = new AlertDialog.Builder(this);dialog.setTitle("刪除主角");//設定顯示視圖為delete_item.xmldialog.setView(delete_view);dialog.setPositiveButton("確定", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){//取得delete_item.xml中的EditText控制項EditText delete_id = (EditText)delete_view.findViewById(R.id.delete_id);//取得輸入的ID值int id = Integer.parseInt(delete_id.getText().toString());//調用資料庫輔助類中的刪除資料方法boolean flag = dbServer.delete(id);if(flag){showToast("主角刪除成功");}else{showToast("主角刪除失敗");}dialog.dismiss();//調用自訂方法更新ListViewSetInAdapter();}});dialog.setNegativeButton("取消", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){//對話方塊取消dialog.dismiss();}});dialog.show();}/** * 更新主角殺死妖怪數 */private void data_update(){//同上final View update_view = LayoutInflater.from(this).inflate(R.layout.update_item, null);AlertDialog.Builder dialog = new AlertDialog.Builder(this);dialog.setTitle("更新主角殺死ID數");dialog.setView(update_view);dialog.setPositiveButton("確定", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){EditText update_id = (EditText)update_view.findViewById(R.id.update_id);int id =Integer.parseInt(update_id.getText().toString());EditText update_number = (EditText)update_view.findViewById(R.id.update_number);String number_str = update_number.getText().toString();boolean flag = dbServer.update(id, number_str);if(flag){showToast("主角資料更新成功");}else{showToast("主角資料更新失敗");}dialog.dismiss();SetInAdapter();}});dialog.setNegativeButton("取消", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){dialog.dismiss();}});dialog.show();}/** * 增加一個主角方法 */private void data_add(){//同上final View add_view = LayoutInflater.from(this).inflate(R.layout.add_item, null);AlertDialog.Builder dialog = new AlertDialog.Builder(this);dialog.setTitle("增加一個主角");dialog.setView(add_view);dialog.setPositiveButton("確定", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){EditText add_name = (EditText)add_view.findViewById(R.id.add_name);String name_str = add_name.getText().toString();EditText add_number = (EditText)add_view.findViewById(R.id.add_number);String number_str = add_number.getText().toString();boolean flag = dbServer.insert(name_str, number_str);if(flag){showToast("主角增加成功");}else{showToast("主角增加失敗");}dialog.dismiss();SetInAdapter();}});dialog.setNegativeButton("取消", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){dialog.dismiss();}});dialog.show();}/* * 按指定內容顯示Toast */protected void showToast(String string){Toast.makeText(this, string, 1).show();}}

這裡有點長,希望大家能夠看完,其實不是太難,這裡:

下一章我們將介紹Android中的單元測試TestCase,謝謝,如果哪位同學想要源碼的,請留郵箱,我會及時給你發過去.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.