2012年5月18日 星期五

SQLite範例

第一步撰寫Activity 主程式
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//Activity主程式
import java.sql.Date;
import java.text.SimpleDateFormat;

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.TextView;


public class SaveTestActivity extends Activity {
    /** Called when the activity is first created. */
 private ActionLogHelper helper;

 private SimpleDateFormat df=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.helper=new ActionLogHelper(this);

        Button saveBt=(Button)findViewById(R.id.saveBtn);
        saveBt.setOnClickListener(new OnClickListener() {
   
   public void onClick(View v) {
    // TODO Auto-generated method stub
    addActionLog("mike");
    queryAndPrintActionLogs();
   }
  });
    }
//此為資料庫寫入
    private void addActionLog(String action){
     SQLiteDatabase db=this.helper.getWritableDatabase();//寫入必須用getWritableDatabase()
     //放資料進入
       ContentValues values =new ContentValues();
     values.put("name", action);
     values.put("time", System.currentTimeMillis());
     db.insertOrThrow(ActionLogHelper.TABLE_NAME, null, values);
    }
//取資料庫資料
    private void queryAndPrintActionLogs(){
     SQLiteDatabase db=this.helper.getReadableDatabase(); //因為取資料所以要
        //用getReadableDatabase()
     Cursor cursor=db.query(ActionLogHelper.TABLE_NAME, new String[]{
       "id","name","time"
     }, null, null, null, null, "time DESC");
     this.startManagingCursor(cursor);
     
     StringBuilder data=new StringBuilder();

     while(cursor.moveToNext()){
      data.append(cursor.getLong(0));
      data.append(" - ");
      data.append(cursor.getString(1));
      data.append(" @ ");
      data.append(df.format(new Date(cursor.getLong(2))));
      data.append("\n");
     }
     TextView msg=(TextView)this.findViewById(R.id.textView1);
     msg.setText(data.toString());
    }
}
第二步建立SQLite資料庫

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//開一個新類別ActionLogHelper


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class ActionLogHelper extends SQLiteOpenHelper {
 private static final String TAG="ActionLog";
 //創建資料庫
 private static final String DB_FILE="game.db";
 private static final int DB_VERSION=1;
 //表格名
 public static final String TABLE_NAME="GameTable";
 
 public ActionLogHelper(Context context) {
  super(context,ActionLogHelper.DB_FILE, null, ActionLogHelper.DB_VERSION);
  // TODO Auto-generated constructor stub
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
  // TODO Auto-generated method stub
//請參考SQL語言
  Log.d(TAG, "onCreate");
  StringBuilder sql =new StringBuilder();
  sql.append("CREATE TABLE "+ActionLogHelper.TABLE_NAME+" (");
  sql.append("ID INTEGER PRIMARY KEY AUTOINCREMENT");
  sql.append(", NAME TEXT NOT NULL");
  sql.append(", TIME INTEGER NOT NULL");
  sql.append(");");
  db.execSQL(sql.toString());
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  // TODO Auto-generated method stub
  Log.d(TAG, "onUpgrade");
  db.execSQL("DROP TABLE IF EXISTS config"); //刪除舊有的資料表
  onCreate(db);
 }

}
第三步main.xml主畫面布置
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <Button
        android:id="@+id/saveBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="存檔" />

</LinearLayout>