Android之SQLite數據庫實例
摘自《Android應用程序開發(第三版)》王向輝、張國印、沈潔編著
1、創建DBAdapter類,用于進行數據庫的操作,具體代碼如下:
package com.example.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class DBAdapter {
private static final String DB_NAME = "people.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_AGE = "age";
public static final String KEY_HEIGHT = "height";
private SQLiteDatabase db;
private final Context context;
private DBOpenHelper dbOpenHelper;
public DBAdapter(Context _context) {
context = _context;
}
/** Close the database */
public void close() {
if (db != null){
db.close();
db = null;
}
}
/** Open the database */
public void open() throws SQLiteException {
dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
try {
db = dbOpenHelper.getWritableDatabase();
}
catch (SQLiteException ex) {
db = dbOpenHelper.getReadableDatabase();
}
}
public long insert(People people) {
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, people.Name);
newValues.put(KEY_AGE, people.Age);
newValues.put(KEY_HEIGHT, people.Height);
return db.insert(DB_TABLE, null, newValues);
}
public People[] queryAllData() {
Cursor results = db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_AGE, KEY_HEIGHT},
null, null, null, null, null);
return ConvertToPeople(results);
}
public People[] queryOneData(long id) {
Cursor results = db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_AGE, KEY_HEIGHT},
KEY_ID + "=" + id, null, null, null, null);
return ConvertToPeople(results);
}
private People[] ConvertToPeople(Cursor cursor){
int resultCounts = cursor.getCount();
if (resultCounts == 0 || !cursor.moveToFirst()){
return null;
}
People[] peoples = new People[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].Age = cursor.getInt(cursor.getColumnIndex(KEY_AGE));
peoples[i].Height = cursor.getFloat(cursor.getColumnIndex(KEY_HEIGHT));
cursor.moveToNext();
}
return peoples;
}
public long deleteAllData() {
return db.delete(DB_TABLE, null, null);
}
public long deleteOneData(long id) {
return db.delete(DB_TABLE, KEY_ID + "=" + id, null);
}
public long updateOneData(long id , People people){
ContentValues updateValues = new ContentValues();
updateValues.put(KEY_NAME, people.Name);
updateValues.put(KEY_AGE, people.Age);
updateValues.put(KEY_HEIGHT, people.Height);
return db.update(DB_TABLE, updateValues, KEY_ID + "=" + id, null);
}
/** 靜態Helper類,用于建立、更新和打開數據庫*/
private static class DBOpenHelper extends SQLiteOpenHelper {
public DBOpenHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
private static final String DB_CREATE = "create table " +
DB_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " +
KEY_NAME+ " text not null, " + KEY_AGE+ " integer," + KEY_HEIGHT + " float);";
@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 " + DB_TABLE);
onCreate(_db);
}
}
}
2、創建People類,具體代碼如下:
package com.example.db;
public class People {
public int ID = -1;
public String Name;
public int Age;
public float Height;
@Override
public String toString(){
String result = "";
result += "ID:" + this.ID + ",";
result += "姓名:" + this.Name + ",";
result += "年齡:" + this.Age + ", ";
result += "身高:" + this.Height + ",";
return result;
}
}
3、在主Activity中(一般是MainActivity,這里是SQLiteDemoActivity),代碼如下:
package com.example.db;
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.TextView;
public class SQLiteDemoActivity extends Activity {
/** Called when the activity is first created. */
private DBAdapter dbAdepter ;
private EditText nameText;
private EditText ageText;
private EditText heightText;
private EditText idEntry;
private TextView labelView;
private TextView displayView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameText = (EditText)findViewById(R.id.name);
ageText = (EditText)findViewById(R.id.age);
heightText = (EditText)findViewById(R.id.height);
idEntry = (EditText)findViewById(R.id.id_entry);
labelView = (TextView)findViewById(R.id.label);
displayView = (TextView)findViewById(R.id.display);
Button addButton = (Button)findViewById(R.id.add);
Button queryAllButton = (Button)findViewById(R.id.query_all);
Button clearButton = (Button)findViewById(R.id.clear);
Button deleteAllButton = (Button)findViewById(R.id.delete_all);
Button queryButton = (Button)findViewById(R.id.query);
Button deleteButton = (Button)findViewById(R.id.delete);
Button updateButton = (Button)findViewById(R.id.update);
addButton.setOnClickListener(addButtonListener);
queryAllButton.setOnClickListener(queryAllButtonListener);
clearButton.setOnClickListener(clearButtonListener);
deleteAllButton.setOnClickListener(deleteAllButtonListener);
queryButton.setOnClickListener(queryButtonListener);
deleteButton.setOnClickListener(deleteButtonListener);
updateButton.setOnClickListener(updateButtonListener);
dbAdepter = new DBAdapter(this);
dbAdepter.open();
}
OnClickListener addButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
People people = new People();
people.Name = nameText.getText().toString();
people.Age = Integer.parseInt(ageText.getText().toString());
people.Height = Float.parseFloat(heightText.getText().toString());
long colunm = dbAdepter.insert(people);
if (colunm == -1 ){
labelView.setText("添加過程錯誤!");
} else {
labelView.setText("成功添加數據,ID:"+String.valueOf(colunm));
}
}
};
OnClickListener queryAllButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
People[] peoples = dbAdepter.queryAllData();
if (peoples == null){
labelView.setText("數據庫中沒有數據");
return;
}
labelView.setText("數據庫:");
String msg = "";
for (int i = 0 ; i<peoples.length; i++){
msg += peoples[i].toString()+"\n";
}
displayView.setText(msg);
}
};
OnClickListener clearButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
displayView.setText("");
}
};
OnClickListener deleteAllButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
dbAdepter.deleteAllData();
String msg = "數據全部刪除";
labelView.setText(msg);
}
};
OnClickListener queryButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
int id = Integer.parseInt(idEntry.getText().toString());
People[] peoples = dbAdepter.queryOneData(id);
if (peoples == null){
labelView.setText("數據庫中沒有ID為"+String.valueOf(id)+"的數據");
return;
}
labelView.setText("數據庫:");
displayView.setText(peoples[0].toString());
}
};
OnClickListener deleteButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
long id = Integer.parseInt(idEntry.getText().toString());
long result = dbAdepter.deleteOneData(id);
String msg = "刪除ID為"+idEntry.getText().toString()+"的數據" + (result>0?"成功":"失敗");
labelView.setText(msg);
}
};
OnClickListener updateButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
People people = new People();
people.Name = nameText.getText().toString();
people.Age = Integer.parseInt(ageText.getText().toString());
people.Height = Float.parseFloat(heightText.getText().toString());
long id = Integer.parseInt(idEntry.getText().toString());
long count = dbAdepter.updateOneData(id, people);
if (count == -1 ){
labelView.setText("更新錯誤!");
} else {
labelView.setText("更新成功,更新數據"+String.valueOf(count)+"條");
}
}
};
}
4、activity_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="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout android:id="@+id/RelativeLayout01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<EditText android:id="@+id/name"
android:text=""
android:layout_width="280dip"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip" >
</EditText>
<TextView android:id="@+id/name_label"
android:text="姓名:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toRightOf="@id/name"
android:layout_alignBaseline="@+id/name">
</TextView>
<EditText android:id="@+id/age"
android:text=""
android:layout_width="280dip"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:layout_below="@id/name"
android:numeric="integer">
</EditText>
<TextView android:id="@+id/age_label"
android:text="年齡:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toRightOf="@id/age"
android:layout_alignBaseline="@+id/age" >
</TextView>
<EditText android:id="@+id/height"
android:layout_width="280dip"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:layout_below="@id/age"
android:numeric="decimal">
</EditText>
<TextView android:id="@+id/height_label"
android:text="身高:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toRightOf="@id/height"
android:layout_alignBaseline="@+id/height">
</TextView>
</RelativeLayout>
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:id="@+id/add"
android:text="添加數據"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding = "5dip"
android:layout_weight="1">
</Button>
<Button android:id="@+id/query_all"
android:text="全部顯示"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding = "5dip"
android:layout_weight="1">
</Button>
<Button android:id="@+id/clear"
android:text="清除顯示"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding = "5dip"
android:layout_weight="1">
</Button>
<Button android:id="@+id/delete_all"
android:text="全部刪除"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding = "5dip"
android:layout_weight="1">
</Button>
</LinearLayout>
<LinearLayout android:id="@+id/LinearLayout03"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:text="ID:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding = "3dip">
</TextView>
<EditText android:id="@+id/id_entry"
android:layout_width="50dip"
android:layout_height="wrap_content"
android:padding = "3dip"
android:layout_weight="1">
</EditText>
<Button android:id="@+id/delete"
android:text="ID刪除"
android:layout_width="50dip"
android:layout_height="wrap_content"
android:padding = "3dip"
android:layout_weight="1">
</Button>
<Button android:id="@+id/query"
android:text="ID查詢"
android:layout_width="50dip"
android:layout_height="wrap_content"
android:padding = "3dip"
android:layout_weight="1">
</Button>
<Button android:id="@+id/update"
android:text="ID更新"
android:layout_width="50dip"
android:layout_height="wrap_content"
android:padding = "3dip"
android:layout_weight="1">
</Button>
</LinearLayout>
<TextView android:id="@+id/label"
android:text="查詢結果:"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<ScrollView android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="@+id/display"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
</ScrollView>
</LinearLayout>
5、測試效果:
(1)頁面顯示
(2)添加一條數據,然后點擊全部顯示,效果如下:
6、總之界面上的效果都實現了,至此,結束。
智能推薦
Android SQlite數據庫使用詳解
目錄 概述 SQLite使用 SQLite數據庫創建 增加數據 刪除數據 更新數據 查詢數據 完整代碼 概述 SQLite 一個非常流行的嵌入式數據庫,它支持 SQL 語言,并且只利用很少的內存就有很好的性能。此外它還是開源的,任何人都可以使用它。 查看模擬器數據庫傳送門:Android Studio查看SQLite數據庫方法大全 SQLite使用 SQLite數據庫創建 Android提供了一個...
Android——SQLite數據庫(簡單操作)
本篇文章源碼:https://github.com/1079374315/HibernateDome 超級簡單的SQLite使用如:(不需要寫任何SQL語句完成以下操作) 1.創建數據庫 1 行代碼 2.添加數據 1 行代碼 3.刪除數據 1 行代碼 4.修改數據 1 行代碼 5.查詢數據 1 行代碼 從創建數據庫到數據庫的增刪查改總共 5 行代碼。 先看效果圖: 如果有興趣咋們跟著小...
Android SQLite數據庫使用
SQLite是一種輕量級的數據庫,存取數據非常快,非常適合移動設備的本地化存取數據。(Android系統中已經內置了SQLite數據庫) 數據庫的創建: SQLiteOpenHelper,該類是Android提供給我們的便于管理數據庫的一個抽象類,里面有兩個主要的抽象方法需要我們在繼承時進行重寫。分別是onCreate():數據庫創建時會調用;onUpgrade():數據庫升級時調用。另外還提供數...
android下的SQLite數據庫
一·創建SQLite數據庫 在com.bmcq.db包中,再創建一個class,即跟MainActivity.java 是同一目錄下,我自己取名為personSQLiteHelper.java. 代碼如下: 然后我們把它布置到手機中后,會在DDMS中找到person.db, 然后用SQLite Expert Person打開它,就會出現下面的情況 此時數據庫就以創建成功! *二、sq...
Android操作SQLite數據庫
文章背景 程序猿或是程序媛們在開發Android項目的時候,難免需要在客戶端數據本地持久化,那么Android中數據本地存儲有四種,分別是SharedPreferences、文件存儲、SQLite存儲數據、ContentProvider存儲數據。其中SQLite它以表的形式存放數據,這種使用表的結構、對于程序員意味著不僅方便存儲各類復雜而且龐大的數據,而且還方便管理數據。 其實Android手機里...
猜你喜歡
Android--SQLite數據庫分頁
如果數據庫特別大,存儲的數據特別多,我們把它加載到適配器控件中,很容易出現內存溢出的情況,并且數據加載的速度也會受到影響。所以我們在加載數據的時候,為了解決這個問題,讓用戶體驗更好,我們可以采用分頁的形式,每次加載10條,或者20條,當用戶去滑動,有查看下一頁的需求時,再次查詢數據庫,進行數據的展示。 要進行數據庫分頁,我們要用到的就是 limit 子句,如下: limit 用到兩個參數,前者是當...
freemarker + ItextRender 根據模板生成PDF文件
1. 制作模板 2. 獲取模板,并將所獲取的數據加載生成html文件 2. 生成PDF文件 其中由兩個地方需要注意,都是關于獲取文件路徑的問題,由于項目部署的時候是打包成jar包形式,所以在開發過程中時直接安照傳統的獲取方法沒有一點文件,但是當打包后部署,總是出錯。于是參考網上文章,先將文件讀出來到項目的臨時目錄下,然后再按正常方式加載該臨時文件; 還有一個問題至今沒有解決,就是關于生成PDF文件...
電腦空間不夠了?教你一個小秒招快速清理 Docker 占用的磁盤空間!
Docker 很占用空間,每當我們運行容器、拉取鏡像、部署應用、構建自己的鏡像時,我們的磁盤空間會被大量占用。 如果你也被這個問題所困擾,咱們就一起看一下 Docker 是如何使用磁盤空間的,以及如何回收。 docker 占用的空間可以通過下面的命令查看: TYPE 列出了docker 使用磁盤的 4 種類型: Images:所有鏡像占用的空間,包括拉取下來的鏡像,和本地構建的。 Con...
requests實現全自動PPT模板
http://www.1ppt.com/moban/ 可以免費的下載PPT模板,當然如果要人工一個個下,還是挺麻煩的,我們可以利用requests輕松下載 訪問這個主頁,我們可以看到下面的樣式 點每一個PPT模板的圖片,我們可以進入到詳細的信息頁面,翻到下面,我們可以看到對應的下載地址 點擊這個下載的按鈕,我們便可以下載對應的PPT壓縮包 那我們就開始做吧 首先,查看網頁的源代碼,我們可以看到每一...