編輯:關於Android編程
Android使用SQLiteOpenHelper 類來輔助使用數據庫,這裡我們來詳細介紹數據庫的crud操作、事務操作、數據庫升級的相關知識。
public class MyDatabaseHelper extends SQLiteOpenHelper{
public static final String CREATE_TABLE = "create table book("
+ "id integer primary key autoincrement, "
+ "author text, "
+ "price real, "
+ "pages integer, "
+ "name text,"
+ "category_id integer)";
//升級數據庫,我們加入了一張新的表
public static final String CREATE_CATEGORY = "create table Category("
+ "id integer primary key autoincrement, "
+ "category_name text, "
+ "category_code integer)";
private Context mContext;
public MyDatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
//onCreate 方法會在調用getReadableDatabase或者WriteableDatabase時並且數據庫不存在時才會被調用,數據庫如果
//已經存在則不會調用。
@Override
public void onCreate(SQLiteDatabase db) {
//創建表
db.execSQL(CREATE_TABLE);
db.execSQL(CREATE_CATEGORY);
Toast.makeText(mContext, "create table successful", Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/*方法1:升級數據庫最粗暴的方法,由於數據庫已經存在時,不會調用onCreate方法,
* 所以刪除表,重新調用onCreate方法,不可取
*/
// db.execSQL("drop table if exists Book");
// db.execSQL("drop table if exists Category");
// onCreate(db);
/*
* 方法2:升級數據庫的最佳實踐,每一個數據庫版本都會對應一個版本號,當指定的數據庫版本號大於當前的版本
* 號的時候,就會進入到onUpgrade()方法中去執行更新操作。這裡需要為每一個版本號賦予它各自改變的內容,然後在
* onUpgrade 方法中執行更新操作
* 這裡來模擬一個數據庫升級的案例
* 第1版本就一個book表
* 第二版本需要新加一個Category表
*
*/
//注意一個細節,這裡我們沒有寫break,為了跨版本升級時都可以執行到
Toast.makeText(mContext, "oldVersion",Toast.LENGTH_LONG).show();
switch (oldVersion) {
case 1:
db.execSQL(CREATE_CATEGORY);
case 2:
db.execSQL("alter table book add column category_id integer");
default:
}
}
}
上面這個類為SQLiteOpenHelper類 ,注意其中onCreate 方法的調用時機,它在我們調用 getReadableDatabase 或者getWriteableDatabase 並且數據庫不存在時會調用一次,如果數據庫的版本變化則會去調用onUpgrade方法去更新數據庫。
布局文件:
MainActivity.java
package com.example.sqllearn;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button createDatabase;
private Button addData;
private Button updateData;
private Button deleteButton;
private Button queryButton;
private Button replaceButton;
MyDatabaseHelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//helper = new MyDatabaseHelper(this, "BookStore.db", null, 1);
//把版本號改為2 進行數據庫的升級
// helper = new MyDatabaseHelper(this, "BookStore.db", null, 2);
helper = new MyDatabaseHelper(this, "BookStore.db", null, 5);
createDatabase = (Button)findViewById(R.id.create_database);
createDatabase.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//調用這一句還沒有數據庫時會調用oncreate方法,否則根據版本信息會調用
//ononUpgrade 方法
helper.getReadableDatabase();
}
});
addData = (Button)findViewById(R.id.add_data);
addData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//添加數據
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "The Da Vinci Code");
values.put("author", "Dan Brown");
values.put("pages", 454);
values.put("price", 16.96);
//插入第一條數據
db.insert("Book", null, values);
values.clear();
//開始組裝第二條數據
values.put("name", "The Lost Symbol");
values.put("author", "Dan Brown");
values.put("pages", 510);
values.put("price", 19.95);
db.insert("Book", null, values); // 插入第二條數據
}
});
updateData = (Button)findViewById(R.id.update_data);
updateData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price", 10.99);
db.update("Book", values,"name=?",new String[]{"The Da Vinci Code"});
}
});
deleteButton = (Button)findViewById(R.id.delete_data);
deleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = helper.getWritableDatabase();
//刪除頁數大於500的書
db.delete("Book","pages>?", new String[]{"500"});
}
});
queryButton = (Button)findViewById(R.id.query_data);
queryButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.query("Book", null, null, null, null, null, null);
if(cursor.moveToFirst()){
do{
// 遍歷Cursor對象,取出數據並打印
String name = cursor.getString(cursor
.getColumnIndex("name"));
String author = cursor.getString(cursor
.getColumnIndex("author"));
int pages = cursor.getInt(cursor
.getColumnIndex("pages"));
double price = cursor.getDouble(cursor
.getColumnIndex("price"));
Toast.makeText(
MainActivity.this,
name + "--" + author + "--" + pages + "--"
+ price, Toast.LENGTH_SHORT).show();
}while(cursor.moveToNext());
}
cursor.close();
}
});
replaceButton = (Button)findViewById(R.id.replace_data);
replaceButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();//開啟事務
try{
db.delete("Book",null, null);
if(true){
//手動拋出一個異常,讓事務失敗,注釋掉這一句則事務執行成功
// throw new NullPointerException();
}
ContentValues values = new ContentValues();
values.put("name", "Game of Thrones");
values.put("author", "George Martin");
values.put("pages", 720);
values.put("price", 20.85);
db.insert("Book", null, values);
db.setTransactionSuccessful(); //事務執行成功
}catch(Exception e){
e.printStackTrace();
}finally{
db.endTransaction();//結束事務
}
}
});
/*
* 使用 Sql 語句操作數據庫
*
*
*/
/*SQLiteDatabase db = openOrCreateDatabase("BookStore.db", MODE_PRIVATE,
null);
db.execSQL(
"insert into Book (name, author, pages, price) values(?, ?, ?, ?)",
new String[] { "The Da Vinci Code", "Dan Brown", "454", "16.96" });
db.execSQL(
"insert into Book (name, author, pages, price) values(?, ?, ?, ?)",
new String[] { "The Lost Symbol", "Dan Brown", "510", "19.95" });
db.execSQL("update Book set price = ? where name = ?", new String[] {
"10.99", "The Da Vinci Code" });
db.execSQL("delete from Book where pages > ?", new String[] { "500" });
db.rawQuery("select * from Book", null);*/
}
}
這裡對代碼做簡單記錄,詳細過程請去看《第一行代碼》這本書,推薦下。
Android pdf viewer在android studio應用問題說明詳解
之前一直是做.NET開發的,最近需要弄一個新聞app,能力有限,只能借助HTML5 WebAPP+android studio來完成這項工作。 android studi
從零開始學android(ScrollView滾動視圖.十八.)
由於手機屏幕的高度有限,所以如果面對組件要顯示多組信息的時候,ScrollView視圖(滾動視圖)可以有效的安排這些組件,浏覽時可以自動的進行滾屏的操作。 android
Android Studio常用插件(較常用的在前面)
JsonOnlineViewer可實現直接在android studio中調試接口數據,可以選擇請求類型,自定義請求頭及請求體,json數據格式化後展示 下載完
Android數據存儲實現的5大方式
數據存儲在開發中是使用最頻繁的,在這裡主要介紹Android平台中實現數據存儲的5種方式,更加系統詳細的介紹了5種存儲的方法和異同。 第一種: 使用SharedPre