124
Android 資資資資資 資資資資資資 資資資 資資資 2012/4 V1 2012/8 V2 Android 資資資資資資資資資 資資資資資資資資

Android 資料庫處理

Embed Size (px)

DESCRIPTION

Android 智慧型手機程式設計 程式設計與應用班. Android 資料庫處理. 建國科技大學 資管系 饒瑞佶 2012/4 V1 2012/8 V2. Android 資料庫- SQLite. 資料庫 SQLite 檔案式資料庫 適合嵌入式系統,不需要額外安裝系統 OPEN SOURCE 資料庫 SQL 指令與一般 DBMS 大同小異,但有些微差異. SQLite. Android. 結構 1. 資料. class DatabaseHelper extends SQLiteOpenHelper. 結構 2. SQL 指令. 資料. - PowerPoint PPT Presentation

Citation preview

Page 1: Android 資料庫處理

Android 資料庫處理

建國科技大學 資管系饒瑞佶

2012/4 V12012/8 V2

Android 智慧型手機程式設計程式設計與應用班

Page 2: Android 資料庫處理

Android 資料庫- SQLite

• 資料庫– SQLite

– 檔案式資料庫– 適合嵌入式系統,不需要額外安裝系統– OPEN SOURCE 資料庫– SQL 指令與一般 DBMS 大同小異,但有些微差異

Page 3: Android 資料庫處理

SQLite

結構 1

資料

結構 2

資料

Android

adb shell + sqlite3+SQL指令

class DatabaseHelper extends SQLiteOpenHelper

SQL指令

Page 4: Android 資料庫處理

SQLite 管理adb shell + sqlite3

提醒…這也只是其中一種方法

Page 5: Android 資料庫處理

SQLite 操作- adb shell

• 沒有 AVD 或是手機

沒有連線的 device

Page 6: Android 資料庫處理

SQLite 操作- adb shell

• 先用 android list avd 看可以用的 AVD

可用的 AVD

Page 7: Android 資料庫處理

SQLite 操作- adb shell

• 再使用 emulator –avd <AVD 名稱 > 啟動一個AVD

• 例如: emulator –avd my_avd –sdcard img 檔位置啟動中的 my_avd

記得要有 sdcard

Page 8: Android 資料庫處理

SQLite 操作- adb shell• my_avd 模擬器

Page 9: Android 資料庫處理

SQLite 操作- adb shell

• 再次執行 adb shell ,就可以看到 # 提示符號

# 提示符號

Page 10: Android 資料庫處理

SQLite 操作- adb shell• 建議進入 sdcard 或 mnt\sdcard 內建立目錄存放資料庫

進入 sdcard

在 sdcard內建立 mydb目錄

進入 mydb目錄

Page 11: Android 資料庫處理

SQLite 操作- adb shell• 請在 # 提示符號後輸入 sqlite3 < 資料庫名

稱 >

• 例如 sqlite3 db1

• 如果資料庫不存在會自動建立,可以看到sqlite> 提示符號

sqlite>提示符號

Page 12: Android 資料庫處理

SQLite 操作- adb shell

• 離開是 .quit ( 注意有一個 .)

• 現在可以開始操作 db1 資料庫• 使用 SQL 指令進行操作,包括:

建立欄位與資料表 ( 結構部分 )建立資料 ( 資料部分 )維護資料 ( 資料部分 )

Page 13: Android 資料庫處理

SQLite 結構相關 SQL 指令

不分大小寫

Page 14: Android 資料庫處理

SQL 指令-結構操作• create table :建立資料表• 藍色是要填資料的部分,其它是固定語法• 所有 SQL 指令都要以 ; 結束

create table 資料表名稱 (

欄位 1 資料型態 ,

欄位 2 資料型態 ,

….

);

create table member( id char(20) not null, name char(20) not null, pwd char(20) not null, age int, PRIMARY KEY(id));

Page 15: Android 資料庫處理

SQL 指令-結構操作• .tables :可以查看目前資料庫內存在的資料表• .help :可以看 sqlite3 所有指令

沒有任何資料表

Page 16: Android 資料庫處理

SQL 指令-結構操作• create table :建立資料表

member資料表已經被建立

Page 17: Android 資料庫處理

SQL 指令-結構操作• .schema :查看資料表結構

member資料表結構

Page 18: Android 資料庫處理

SQL 指令-結構操作• alter table :更改資料表結構

alter table 資料表名稱 add 欄位 1 資料型態 ;

增加欄位

alter table 資料表名稱 rename to 新資料表名稱 ;

更改資料表名稱

• drop table :刪除資料表

drop table 資料表名稱 ;

Page 19: Android 資料庫處理

SQLite 資料相關 SQL 指令

Page 20: Android 資料庫處理

SQL 指令-資料操作• insert :新增資料所有資料都要加上單引號

insert into 資料表名稱 ( 欄位 1, 欄位 2…) values (‘ 資料 1’,’ 資料2’…);

已在 member資料表中新增一筆資料

Insert into member (id,name,pwd,age) values ('A123','小叮噹 ','1111',20);

Page 21: Android 資料庫處理

SQL 指令-資料操作• Select:篩選資料

select 欄位 s from 資料表名稱 where 條件 ;

加入 where條件

Select * from member;

Page 22: Android 資料庫處理

SQL 指令-資料操作• update:更新資料

update 資料表名稱 set 欄位 =‘ 新值’… where 條件 ;

姓名改成大寶

update member set name=‘大寶 ' where id='A123';

Page 23: Android 資料庫處理

SQL 指令-資料操作• delete:刪除資料

Delete from 資料表名稱 where 條件 ;

先新增一筆資料

刪除剛新增的資料

delete from member where id='A123';

Page 24: Android 資料庫處理

SQL 指令-結構操作

• SQLite 沒有刪除欄位的指令,例如 ALTER TABLE DROP COLUMN

• 那怎麼辦?

Page 25: Android 資料庫處理

SQL 指令-結構操作新增一個備份資料庫 member_backup

將資料從 member搬到 member_backup刪除 member

再新增一個 member,此時不要含要刪掉的欄位再把資料從 member_backup搬到member

刪除 member_backup

完成

Page 26: Android 資料庫處理

更多 SQLite SQL 指令• http://www.newobjects.com/pages/ndl/

SQLite3/sql.htm#ALTER TABLE

Page 27: Android 資料庫處理

SQLite+Android

By SQLiteOpenHelper

Page 28: Android 資料庫處理

SQLite+Android

• 建立新專案- HelloDB

Page 29: Android 資料庫處理

Android+SQLite 使用方式

• 引用 class SQLiteOpenHelper

• 建立 SQLiteOpenHelper 物件• 透過 SQLiteOpenHelper 物件建立

database 物件• 透過 database 物件存取資料

記得要開 android.permission.WRITE_EXTERNAL_STORAGE

Page 30: Android 資料庫處理

SQLiteOpenHelper 運作架構

class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, “db2.db", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE_TABLE); //新增資料表 } @Override public void onUpgrade(SQLiteDatabase db, int oldV, int newV) { }}

只有在資料庫不存在時才執行

只有在DatabaseHelper此建構子有執行時才執行

資料庫版本有更新時才執行

與 APK建立在一起

Page 31: Android 資料庫處理

SQLite+Android• 首先,在主程式中加入 SQLiteOpenHelper結構

資料庫第一次建立時會執行 onCreate

資料庫異動版本時會執行 onUpgrade

必要的 class

建立 db2.db資料庫

Page 32: Android 資料庫處理

SQLite+Android• SQLiteOpenHelper結構

// SQLite資料庫使用必要 class ------------------------ String DATABASE_TABLE = "member"; String DATABASE_CREATE_TABLE = "create table " + DATABASE_TABLE + "(_id char(20), name, pwd, age, primary key(_id));"; class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, "/sdcard/db2.db", null, 1); } @Override public void onCreate(SQLiteDatabase db) {

} @Override public void onUpgrade(SQLiteDatabase db, int oldV, int newV) { }}

如果要建立到sdcard

Page 33: Android 資料庫處理

SQLite+Android• 從 class HelloDB 呼叫 DatabaseHelper 建立資料庫 建立 DatabaseHelper物件

呼叫建立 db2.db資料庫

Page 34: Android 資料庫處理

code

DatabaseHelper dbHelper;SQLiteDatabase db;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_db); dbHelper=new DatabaseHelper(this); db=dbHelper.getWritableDatabase(); }

Page 35: Android 資料庫處理

SQLite+Android

• 資料庫被建立在 data/data/com.android.hellodb

Page 36: Android 資料庫處理

SQLite+Android• 資料庫被建立在 data/data/com.android.hellodb

Page 37: Android 資料庫處理

SQLite+Android• 有資料庫後,下一步要建立資料

新增資料

建立資料表

定義資料表結構

Page 38: Android 資料庫處理

String cmd="insert into " + DATABASE_TABLE + " (_id,name,pwd,age) values ('c123','小黑 ','ccc',12)";

db.execSQL(cmd);

• 建立資料

Page 39: Android 資料庫處理

SQLite+Android

• 為何會錯誤?

跟執行流程或資料庫設定有關!

Page 40: Android 資料庫處理

SQLite+Android

• 幾點注意!1. 下面這段只有在資料庫第一次被建立時才會進行,所以如

果資料庫已經存在,那就不會建立資料表,當然也就不能寫入資料

上張投影片的錯誤就是因為我們已經先建立 db2.db ,因此再次執行程式時,並不會建立資料表,導致下面程式出錯

Page 41: Android 資料庫處理

SQLite+Android• 正常執行結果

資料庫

資料表

資料

中文資料有亂碼

Page 42: Android 資料庫處理

到此為止,同樣的程式再執行一次會出現錯誤, WHY ?

Page 43: Android 資料庫處理

SQLite+Android

• 最後,可以進行資料查詢

再新增一筆資料 ( 小黑 )

SQL查詢指令資料移動到第一筆

顯示資料

Page 44: Android 資料庫處理

String cmd_select="select * from " + DATABASE_TABLE; Cursor c=db.rawQuery(cmd_select, null); c.moveToNext(); String data=""; for(int i=1;i<=c.getCount();i++){ for(int j=1;j<=c.getColumnCount();j++){ data +=c.getString(j-1); } data +="\n"; c.moveToNext(); }new AlertDialog.Builder(HelloDB.this).setTitle("data").setMessage(data).setPositiveButton("確認 ",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }).show();

Page 45: Android 資料庫處理

SQLite+Android

• 實際顯示沒有亂碼

Page 46: Android 資料庫處理

小練習• 使用上述課程 member 資料表• 設計一個登入畫面,可以讓使用者輸入帳號與密碼

• 輸入完成後按下「確認」按鈕後,連回資料庫內的 member 資料表進行確認 (id 與pwd 欄位 )

• 輸入正確者跳至下一個頁面 ( 自訂 ) ,錯誤者請跳出訊息提示框

Page 47: Android 資料庫處理

透過 ListView 顯示資料庫資料

Page 48: Android 資料庫處理

透過 ListView 顯示資料整個版面都用 ListActivity

改成 ListActivity

刪除

Page 49: Android 資料庫處理

透過 ListView 顯示資料

陣列資料

ArrayAdapter

Page 50: Android 資料庫處理

透過 ListView 顯示資料

陣列資料 private static final String[] mStrings = new String[] { "大餅包小餅 ", "蚵仔煎 ", "東山鴨頭 ", "臭豆腐 ", "潤餅 ", "豆花 ", "青蛙下蛋 ","豬血糕 ", "大腸包小腸 ", "鹹水雞 ", "烤香腸 ","車輪餅 ","珍珠奶茶 ","鹹酥雞 ","大熱狗 ", "炸雞排 ","山豬肉 ","花生冰 ","剉冰 ","水果冰 ", "包心粉圓 ","排骨酥 ","沙茶魷魚 ","章魚燒 ","度小月 ", "aaa","abc","bbb","bcd","123" };

setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mStrings));

getListView().setTextFilterEnabled(true);

Page 51: Android 資料庫處理

透過 ListView 顯示資料

選了怎麼不會勾選 ?

Page 52: Android 資料庫處理

透過 ListView 顯示資料

ListView勾選效果

加入:ListView lv = this.getListView();lv.setChoiceMode( ListView.CHOICE_MODE_SINGLE );

修改: android.R.layout.simple_list_item_checked

Page 53: Android 資料庫處理

透過 ListView 顯示資料

偵測選擇資料

Page 54: Android 資料庫處理

Object o=this.getListAdapter().getItem(position);String keyword=o.toString();Toast.makeText(HelloDB.this, "choose:" + keyword,

Toast.LENGTH_SHORT).show();

Page 55: Android 資料庫處理

透過 ListView 顯示資資料

Page 56: Android 資料庫處理

把資料庫與 ListView 合起來

方法一

Page 57: Android 資料庫處理

把資料庫與 ListView 合起來

Page 58: Android 資料庫處理

把資料庫與 ListView 合起來 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dbHelper=new DatabaseHelper(this); db=dbHelper.getWritableDatabase(); String cmd_select="select * from " + DATABASE_TABLE; Cursor c=db.rawQuery(cmd_select, null); c.moveToNext(); //取得資料後放到陣列mStrings String[] mStrings = new String[c.getCount()]; for(int i=1;i<=c.getCount();i++){ mStrings[i-1]=new String(c.getString(1)); c.moveToNext(); } //顯示資料 setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mStrings)); }

Page 59: Android 資料庫處理

透過 ListView 顯示資料

• 假設是在 Activity 中除了 ListView之外,還要放入其他的組件時,這時候就需要在 Activity 中加入一個ListView 物件,利用這個組件的setAdapter來連接 Adapter

Page 60: Android 資料庫處理

透過 ListView 顯示資料

ListView物件的 id

main.xml版面

Page 61: Android 資料庫處理

透過 ListView 顯示資料

陣列資料

不改

Page 62: Android 資料庫處理

透過 ListView 顯示資料

偵測選擇資料

如果是顯示兩個欄位以上資料Cursor c = (Cursor) arg0.getItemAtPosition(position);String tableValue = c.getString(0);

Page 63: Android 資料庫處理

CODE

list.setOnItemClickListener(new OnItemClickListener(){public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {// TODO Auto-generated method stubString keyword=list.getItemAtPosition(arg2).toString();Toast.makeText(MyDB_ListView.this, "choose:" + keyword, Toast.LENGTH_SHORT).show();} });

Page 64: Android 資料庫處理

透過 ListView 顯示資料• ArrayAdapter 中有一個 android 定義好的內建 list 樣式 -

“android.R.layout.simple_list_item_1” ,其它樣式如下所列:– android.R.layout.simple_list_item_1 :一行 text

– android.R.layout.simple_list_item_2 :一行 text較大,一行 text較小– android.R.layout.simple_list_item_single_choice :單選– android.R.layout.simple_list_item_multiple_choice :多選按鈕– android.R.layout.simple_list_item_checked :勾選盒

• 第 1 個剛剛有用了,事實上第 3,4,5 個也是直接換上去就可以看到了。

• 第 2 個 android.R.layout.simple_list_item_2 就比較麻煩,原因是 ArrayAdapter 並不支援傳入兩個字串參數值,所以要改用SimpleAdapter ,而且傳入的數值型態要改為 ArrayList 才可以要加上 list.setChoiceMode( ListView.CHOICE_MODE_SINGLE );選擇才會有變色

Page 65: Android 資料庫處理

透過 ListView 顯示資料- SimpleAdapter

ArrayList

SimpleAdapter

Page 66: Android 資料庫處理

透過 ListView 顯示資料- SimpleAdapter

陣列資料

Page 67: Android 資料庫處理

code @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 將資料放入陣列 for(int i=0;i<mPlaces.length;i++){ HashMap<String,String> item=new HashMap<String,String>(); item.put("food",mFoods[i]); item.put("place",mPlaces[i]); list.add(item); } //設定顯示的資料 SimpleAdapter adapter=new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, new String[]{"food","place"}, new int[]{android.R.id.text1,android.R.id.text2}); //顯示資料 setListAdapter(adapter); }

Page 68: Android 資料庫處理

透過 ListView 顯示資料- SimpleAdapter

陣列資料 private static final String[] mPlaces = new String[] { "台北市 ", " 新北市 ", "台南市 ", "高雄市 ", "苗粟縣 ", "台北市 ", " 新北市 ", "台南市 ", "高雄市 ", "苗粟縣 ", "台北市 ", " 新北市 ", "台南市 ", "高雄市 ", "苗粟縣 ", "台北市 ", " 新北市 ", "台南市 ", "高雄市 ", "苗粟縣 ", "台北市 ", " 新北市 ", "台南市 ", "高雄市 ", "苗粟縣 ", "台北市 ", " 新北市 ", "789", "cde", "abc" }; private static final String[] mFoods = new String[] { " 大餅包小餅 ", "蚵仔煎 ", "東山鴨頭 ", "臭豆腐 ", "潤餅 ", "豆花 ", "青蛙下蛋 ","豬血糕 ", " 大腸包小腸 ", "鹹水雞 ", "烤香腸 ","車輪餅 ","珍珠奶茶 ","鹹酥雞 "," 大熱狗 ", "炸雞排 ","山豬肉 ","花生冰 ","剉冰 ","水果冰 ", " 包心粉圓 ","排骨酥 ","沙茶魷魚 ","章魚燒 ","度小月 ", "aaa","abc","bbb","bcd","123" };

Page 69: Android 資料庫處理

透過 ListView 顯示資料- SimpleAdapter

Page 70: Android 資料庫處理

透過 ListView 顯示資料- SimpleAdapter

偵測選擇資料

偵測選擇資料

Page 71: Android 資料庫處理

code

@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {// TODO Auto-generated method stubsuper.onListItemClick(l, v, position, id);String keyword=((HashMap)l.getItemAtPosition(position)).get("place").toString();Toast.makeText(SimpleAdap.this, "choose:" + keyword, Toast.LENGTH_SHORT).show();}

Page 72: Android 資料庫處理

透過 ListView 顯示資料-自訂版面

• 如果不要用 android 內建的 simple_list_item_2 ,改用自己定義的樣式,要怎麼作呢?像上面的範例,再加上一個評分的字串在地點的旁邊。

• 首先先製作一個專用的 layout ,取名為mylistview.xml。

Page 73: Android 資料庫處理

透過 ListView 顯示資料-自訂版面<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="match_parent" android:layout_width="fill_parent" android:orientation="vertical"> <TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="6dip" android:layout_marginTop="6dip" android:textAppearance="?android:attr/textAppearanceLarge"> </TextView> <LinearLayout android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/linearLayout1" android:orientation="horizontal"> <TextView android:id="@+id/textView2" android:text="TextView" android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall"> </TextView> <TextView android:text="TextView" android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_marginLeft="6dip"> </TextView> </LinearLayout></LinearLayout>

mylistview.xml

Page 74: Android 資料庫處理

透過 ListView 顯示資料-自訂版面

第二個 LinearLayout要設定成 horizontal

Page 75: Android 資料庫處理

透過 ListView 顯示資料-自訂版面

三個改變的地方

Page 76: Android 資料庫處理

code @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 將資料放入陣列 for(int i=0;i<mPlaces.length;i++){ HashMap<String,String> item=new HashMap<String,String>(); item.put("food",mFoods[i]); item.put("place",mPlaces[i]); item.put("rating",mRatings[i]); list.add(item); } //設定顯示的資料 SimpleAdapter adapter=new SimpleAdapter(this, list, R.layout.mylistview, new String[]{"food","place","rating"}, new int[]{R.id.textView1,R.id.textView2,R.id.textView3}); //顯示資料 setListAdapter(adapter); }

Page 77: Android 資料庫處理

透過 ListView 顯示資料-自訂版面

private static final String[] mRatings = new String[] { "1", "2", "4", "3", "5", "3", "2", "4", "1", "1", "3", "3", "3", "1", "3", "3", "5", "2", "5", "2", "5", "3", "1", "2", "2", "2", "3", "1", "2", "3" };

陣列資料

Page 78: Android 資料庫處理

透過 ListView 顯示資料-自訂版面

Page 79: Android 資料庫處理

透過 ListView 顯示資料-加入圖片• 最後加入圖 片到 ListView吧• 圖片需要先放到 res/drawable-xxxx 目錄中(這裡放到 res/drawable-hdpi 中)

• 因為 HashMap 的 value 部份需要用到圖片,是一個 int 的型態,所以 HashMap 的 value 部份需要改為 Object ,才能容得下 int 和 string的類型。

• 修改 mylistview.xml ,加上圖片在標題的左邊

Page 80: Android 資料庫處理

透過 ListView 顯示資料-加入圖片

再加入 LinearLayout 與 ImageView

LinearLayout要設定成 horizontal

Page 81: Android 資料庫處理

透過 ListView 顯示資料-加入圖片

三個修改的地方

Page 82: Android 資料庫處理

透過 ListView 顯示資料-加入圖片

private static final int[] mPics=new int[]{ R.drawable.pic1,R.drawable.pic2,R.drawable.pic3, R.drawable.pic4,R.drawable.pic5, R.drawable.pic1,R.drawable.pic2,R.drawable.pic3, R.drawable.pic4,R.drawable.pic5, R.drawable.pic1,R.drawable.pic2,R.drawable.pic3, R.drawable.pic4,R.drawable.pic5, R.drawable.pic1,R.drawable.pic2,R.drawable.pic3, R.drawable.pic4,R.drawable.pic5, R.drawable.pic1,R.drawable.pic2,R.drawable.pic3, R.drawable.pic4,R.drawable.pic5, R.drawable.pic1,R.drawable.pic2,R.drawable.pic3, R.drawable.pic4,R.drawable.pic5 };

陣列資料

Page 83: Android 資料庫處理

透過 ListView 顯示資料-加入圖片

陣列資料

Page 84: Android 資料庫處理

ListView + 資料庫方法二 ( 有限制 )

Page 85: Android 資料庫處理

透過 ListView 顯示資料庫資料原程式,用 Toast顯示資料

用 ListView取代這裡

Page 86: Android 資料庫處理

透過 ListView 顯示資料庫資料• 注意資料表內需要有個 _id的主鍵欄位• 注意使用 ListView顯示資料 ,需要修改 extends Activity變成 ListActivity

• 需刪掉 setContentView(R.layout.main);

Page 87: Android 資料庫處理

透過 ListView 顯示資料庫資料

String[] from = new String[]{"name","pwd","_id"}; //一定要有 _id才行 int[] to = new int[]{android.R.id.text1};

Cursor c1 = db.query("member", from, null, null, null, null, "_id ASC");startManagingCursor(c1);//多資料欄位ListAdapter adapter = new SimpleCursorAdapter(this,android.R.layout. two_line_list_item,c1,new String[] {"name","pwd"},new int[] {android.R.id.text1, android.R.id.text2 }); setListAdapter(adapter);

Page 88: Android 資料庫處理

透過 ListView 顯示資料庫資料

Page 89: Android 資料庫處理

透過 ListView 顯示資料庫資料• 兩列字體大小不同

改這個屬性

原來是two_line_list_item

Page 90: Android 資料庫處理

透過 ListView 顯示資料庫資料

Page 91: Android 資料庫處理

透過 ListView 顯示資料庫資料

偵測選擇資料

直接顯示資料

Page 92: Android 資料庫處理

@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {super.onListItemClick(l, v, position, id);// Get the item that was clicked//直接顯示資料Cursor cursor = (Cursor)this.getListAdapter().getItem(position);String keyword =cursor.getString(cursor.getColumnIndex("_id"));Toast.makeText(this, "您選擇了 : " + keyword, Toast.LENGTH_LONG).show();}

透過 ListView 顯示資料庫資料偵測選擇資料

Page 93: Android 資料庫處理

透過 ListView 顯示資料庫資料

傳送資料

透過另一頁 (DataDetails)顯示資料注意要加入 <activity android:name="DataDetails"></activity>

Page 94: Android 資料庫處理

透過 ListView 顯示資料庫資料透過另一頁 (DataDetails)顯示資料注意要加入 <activity android:name="DataDetails"></activity>

@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {super.onListItemClick(l, v, position, id);// Get the item that was clicked//* 跳頁顯示資料 Intent intent = new Intent(this, DataDetails.class); Cursor cursor = (Cursor)this.getListAdapter().getItem(position); intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id"))); startActivity(intent); }

Page 95: Android 資料庫處理

透過 ListView 顯示資料庫資料

接收資料

DataDetails.java

Page 96: Android 資料庫處理

CODE

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.details); employeeID=getIntent().getIntExtra("EMPLOYEE_ID", 0); Toast.makeText(this, "您選擇了: "+ employeeID, Toast.LENGTH_LONG).show(); }

Page 97: Android 資料庫處理

資料刪修

新增 / 修改 / 刪除

Page 98: Android 資料庫處理

新增• 加入版面 main1.xml

Page 99: Android 資料庫處理

新增

EditText 動態 SQL指令

跳回顯示頁面

Page 100: Android 資料庫處理

新增 dbHelper = new DatabaseHelper(this); db = dbHelper.getWritableDatabase(); tv1=(EditText)findViewById(R.id.editText1); tv2=(EditText)findViewById(R.id.editText2); tv3=(EditText)findViewById(R.id.editText3); tv4=(EditText)findViewById(R.id.editText4); bt1=(Button)findViewById(R.id.button1); /* 新增的 Button */ bt1.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { String cmd="insert into member (_id, name, pwd, age) values ('" + tv1.getText() + "','" + tv3.getText() + "','" + tv2.getText() + "'," + tv4.getText() + ");"; db.execSQL(cmd); // 執行 SQL指令,進行資料新增 Toast.makeText(NewData.this, "資料新增完成 ", Toast.LENGTH_LONG).show(); Intent it1=new Intent(); it1.setClass(NewData.this, ListViewDB.class); startActivity(it1); NewData.this.finish(); } });

Page 101: Android 資料庫處理

修改• 加入版面 main.xml

Page 102: Android 資料庫處理

修改 I

先取得要修改的資料 將查到的資料

填入輸入框

Page 103: Android 資料庫處理

修改 II

Page 104: Android 資料庫處理

修改 dbHelper = new DatabaseHelper(this); db = dbHelper.getWritableDatabase(); tv1=(EditText)findViewById(R.id.editText1); tv2=(EditText)findViewById(R.id.editText2); tv3=(EditText)findViewById(R.id.editText3); bt1=(Button)findViewById(R.id.button1); mID = this.getIntent().getExtras().getString("EMPLOYEE_ID");

// 查詢資料 String cmd_select="select * from member where _id='" + mID + "';"; //Toast.makeText(DataDetails.this, cmd_select, Toast.LENGTH_LONG).show(); Cursor c = db.rawQuery(cmd_select, null); // 執行 SQL指令,進行資料查詢 if(c.moveToFirst()){ //有資料才顯示 tv1.setText(c.getString(2)); //密碼 tv2.setText(c.getString(c.getColumnIndex("name"))); //姓名 tv3.setText(String.valueOf(c.getInt(c.getColumnIndex("age")))); //年齡 //c.close(); }else{ Toast.makeText(DataDetails.this, "找不到任何資料 ", Toast.LENGTH_LONG).show(); return; } /* 修改的 Button */ bt1.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { String cmd="update member set name='" + tv2.getText() + "',pwd='" + tv1.getText() + "',age=" + tv3.getText() + " where _id='" + mID + "';"; db.execSQL(cmd); // 執行 SQL指令,進行資料修改 Toast.makeText(DataDetails.this, "資料修改完成 ", Toast.LENGTH_LONG).show(); } });

Page 105: Android 資料庫處理

小迷思• 應改成 cursor.getString ,否則將取不到值

• 接收端: mID = this.getIntent().getExtras().getString("EMPLOYEE_ID");

Page 106: Android 資料庫處理

刪除

/* 刪除的 Button */ bt2.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { db.delete("member", "_id='" + mID + "'", null); Toast.makeText(DataDetails.this, "資料刪除完成 ", Toast.LENGTH_LONG).show(); } });

Page 107: Android 資料庫處理

選 單• 使用手機硬體上的 MENU鍵進行呼叫顯示• 建立選單

– onCreateOptionsMenu

• 處理選項動作– onOptionsItemSelected

Page 108: Android 資料庫處理

選單基本結構• 建立選單

– onCreateOptionsMenu

• 處理選項動作– onOptionsItemSelected

Page 109: Android 資料庫處理

加入選單選項• 加入選項

– menu.add(0, 識別符號 , 0, 顯示文字 )

menu.add(0, MENU_ABOUT, 0, "關於 BMI").setIcon(android.R.drawable.ic_menu_help);menu.add(0, MENU_QUIT, 0, "結束BMI").setIcon(android.R.drawable.ic_menu_close_clear_cancel);

Page 110: Android 資料庫處理

選 單

Page 111: Android 資料庫處理

處理選項動作• 處理選項動作

– onOptionsItemSelected

Page 112: Android 資料庫處理

protected static final int MENU_ABOUT=Menu.FIRST; protected static final int MENU_QUIT=Menu.FIRST+1;@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// TODO Auto-generated method stubmenu.add(0, MENU_ABOUT, 0, "關於 BMI").setIcon(android.R.drawable.ic_menu_help);menu.add(0, MENU_QUIT, 0, "結束 BMI").setIcon(android.R.drawable.ic_menu_close_clear_cancel);return super.onCreateOptionsMenu(menu);}

@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// TODO Auto-generated method stubswitch(item.getItemId()){case MENU_ABOUT:

break;case MENU_QUIT:

break;}return super.onOptionsItemSelected(item);}

Page 113: Android 資料庫處理

小練習• 在 DataDetails 上設計四個 TextView 物件• 透過傳進來的 EMPLOYEE_ID ,再到資料庫查詢詳細資料,將其顯示到上面四個TextView 中

Page 114: Android 資料庫處理

預告怎麼連結外部 DB

透過 WebService透過 HttpPost 或 HttpGet

Page 115: Android 資料庫處理

資料庫補充

Page 116: Android 資料庫處理

SQLite Manager

透過它的介面管理 SQLite

Page 117: Android 資料庫處理

SQLite Manager• FireFox 外掛

– https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/

• 直接點選安裝

Page 118: Android 資料庫處理

SQLite Manager直接開啟 SQLIte database

有 UI介面比較好操作

Page 119: Android 資料庫處理

SQLite Manager

• 實體手機可以開啟 USB 連結模式,透過外接碟模式被開啟

• AVD 內的資料庫可以透過 adb pull拉出,設定後再用 adb push 存回,或使用 ddms來完成

Page 120: Android 資料庫處理

動態 SQL 指令

撰寫動態 SQL 指令的步驟

Page 121: Android 資料庫處理

動態 SQL 指令• 全部都從基本指令開始• 欄位型態是文字或日期,對應的值要加單引號• 注意空白• 不分大小寫• 新增

– Insert into 資料表 ( 欄位 s) values ( 值 s)• 刪除

– delete from 資料表 where 條件• 修改

– update 資料表 set 欄位 s= 新值 s where 條件• 查詢

– select 欄位 from 資料表 [where 條件 ]

Page 122: Android 資料庫處理

動態 SQL 指令

1. 用假資料先寫出正確的 SQL 指令 對不對,問 SQLite

2. 用程式取代假資料3. 用雙引號將程式與原 SQL 指令切開

SQL 指令是字串,與程式要切開4. 用加號將切開位置串起來

把最後完成的結果貼回程式內

Page 123: Android 資料庫處理

動態 SQL 指令1.用假資料先寫出正確的 SQL 指令

update member set name=‘aaa’,age=55 where _id =‘A123’2.用程式取代假資料

update member set name=‘name.getText()’,age=age.getText() where _id =‘get_id’

3.用雙引號將程式與原 SQL 指令切開update member set name=‘”name.getText()”’,age=“age.getText() “ where _id =‘”get_id”’

4.用加號將切開位置串起來update member set name=‘” + name.getText() + ”’,age=“ + age.getText() + “ where _id =‘” + get_id + ”’

Page 124: Android 資料庫處理

動態 SQL 指令1.用假資料先寫出正確的 SQL 指令

Select * from member where _id =‘A123’2.用程式取代假資料

Select * from member where _id=‘get_id’3.用雙引號將程式與原 SQL 指令切開

Select * from member where _id=‘” get_id ”%’4.用加號將切開位置串起來

Select * from member where _id=‘” + get_id + ”’