這一章我們來學習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);
}
/**
* 創建表
*/
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DB_CREATE);
}
/**
* 更新表
*/
@Override
public 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);
//插入數據,返回插入數據ID
long 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;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.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);
}
@Override
public 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.xml
dialog.setView(delete_view);
dialog.setPositiveButton("確定", new DialogInterface.OnClickListener()
{
@Override
public 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();
//調用自定義方法更新ListView
SetInAdapter();
}
});
dialog.setNegativeButton("取消", new DialogInterface.OnClickListener()
{
@Override
public 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()
{
@Override
public 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()
{
@Override
public 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()
{
@Override
public 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()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
dialog.show();
}
/*
* 按指定內容顯示Toast
*/
protected void showToast(String string)
{
Toast.makeText(this, string, 1).show();
}
}
這裡有點長,希望大傢能夠看完,其實不是太難,這裡上圖:
下一章我們將介紹Android中的單元測試TestCase,謝謝,如果哪位同學想要源碼的,請留郵箱,我會及時給你發過去.
摘自:kangkangz4的專欄