總網頁瀏覽量

關於我自己

我的相片
人生的必修課是接受無常,人生的選修課是放下執著。

2012年1月18日 星期三

How to use SQLite







為了讓user對AP所做的變更能保留下來, 本範例加入SQLite來儲存資料.

開始先建立一個資料表"l_listData",其欄位有兩個: "l_id", "l_data", 代表資料ID與資料字串.

ID是資料庫中自動增加的整數, 讓我們用cursor篩選時可由l_id找到該筆資料並做處理.

得到資料表欄位總數:cursor.getColumnCount()
得到傳回資料表的資料筆數:cursor.getCount()
得到資料表第index欄的欄名:cursor.getColumnName(0)
得到欄名為name的index:cursor.getColumnIndex("name")

ListView_malloc_SQLite.java
package com.tsots.ListView_malloc_SQLite;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class ListView_malloc_SQLite extends Activity
{
 String tables[] = {"l_listData"};
 String[] updateFields = 
 { 
    "l_data"
 };
 String fieldNames[][] =
 {
    { "l_id", "l_data"}
 }; 
 String fieldTypes[][] =
 {
    { "INTEGER PRIMARY KEY AUTOINCREMENT", "text"}
 };
 int version = 1;
 private MySQLiteOpenHelper dbHelper = new MySQLiteOpenHelper (
                  this,
                  "SQLite_LsitView.db",
                  null, 
                  version,    /*version*/ 
                  tables, 
                  fieldNames, 
                  fieldTypes
                 );
 Context context = ListView_malloc_SQLite.this;
 String tag = "ListView_malloc_SQLite.this";
 String[] countriesStr;
 TextView myTextView;
 EditText myEditText;
 Button myButton_add;
 Button myButton_remove;
 ListView listview;
 ArrayAdapter adapter2;
 List allData;
 List allId;
 String newData;
 int click_id;
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
       
     myTextView = (TextView) findViewById(R.id.myTextView);
     myEditText = (EditText) findViewById(R.id.myEditText);
     myButton_add = (Button) findViewById(R.id.myButton_add);
     myButton_remove = (Button) findViewById(R.id.myButton_remove);
     listview = (ListView) findViewById(R.id.listview1); 
     
     countriesStr = getResources().getStringArray(R.array.array_listview);
     
     default_sqlite_data();
     load_sqlite_data();
     
     listview.setOnItemClickListener(new ListView.OnItemClickListener()
     {
      public void onItemClick(AdapterView arg0, View arg1, int id, long arg3) 
      {
       myTextView.setText(allData.get(id)); 
       myEditText.setText(allData.get(id));
       click_id = id;
       System.out.println("select: "+ arg3);
      }
     });
     
     myButton_add.setOnClickListener(new Button.OnClickListener()
     {
      public void onClick(View arg0)
      {
       newData = myEditText.getText().toString();
       for (int i = 0; i < adapter2.getCount(); i++)
       {
        //若此筆資料已存在列表中, 則不加入
        if (newData.equals(adapter2.getItem(i)))
        {
         return;
        }
       }       
       if (!newData.equals(""))
       {
        //寫入資料庫
        String[] updateFields = {"l_data"};
        String[] updateValues = {newData};
        dbHelper.insert(tables[0], updateFields, updateValues);
        //重新讀取一次資料庫
        load_sqlite_data();
        
        int position = adapter2.getPosition(newData);
        listview.setSelection(position);
        myEditText.setText("");
        Log.i(tag, "add a new data: "+newData);
       }
      }
     });    
    
     myButton_remove.setOnClickListener(new Button.OnClickListener()
     {
      public void onClick(View arg0)
      {
       if (myEditText.getText().toString() != "")
       {
        //從資料庫刪除
        String where = "l_id=?";
           String[] whereValue = {allId.get(click_id)};          
        dbHelper.delete(tables[0], where, whereValue);
        //重新讀取一次資料庫
        load_sqlite_data();

        myEditText.setText("");
        if (adapter2.getCount() == 0)
        {
         myTextView.setText("");
        }
        Log.i(tag, "delete a data: "+allData.get(click_id)+" from SQLite");
       }
      }
     });     
 }
 
 public void default_sqlite_data()
 {
  Cursor cursor1 = null;
  try
  {
   cursor1 = dbHelper.select(tables[0], null, null, null, null, null, null);
   System.out.println("cursor1.getCount() = "+cursor1.getCount());
   if(cursor1.getCount() == 0)
   {
    String[] updateFields2 = {"l_data"};
    cursor1.moveToFirst();
    System.out.println("total data = "+countriesStr.length);
    for(int i=0 ; i();
   allId = new ArrayList();
   while (cursor_listdata.moveToNext())
   {
    allId.add(cursor_listdata.getString(0));
    allData.add(cursor_listdata.getString(1));  
   }
   adapter2 = new ArrayAdapter(this,android.R.layout.simple_list_item_1, allData);
   listview.setAdapter(adapter2);
  }
  catch(Exception e)
  {
   Log.e(tag, e.toString());
  }
  finally
  {
   cursor_listdata.close();
  }  
 }
}//


select(): 查詢資料表
insert(): 新增一筆資料
delete(): 刪除一筆資料
update(): 更新資料表

MySQLiteOpenHelper.java
package com.tsots.ListView_malloc_SQLite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class MySQLiteOpenHelper extends SQLiteOpenHelper

{

  public String TableNames[];

  public String FieldNames[][];

  public String FieldTypes[][];

  public static String NO_CREATE_TABLES = "no tables";

  private String message = "";

  

  public MySQLiteOpenHelper(Context context, String dbname, CursorFactory factory, int version, String tableNames[], String fieldNames[][], String fieldTypes[][])

  {

    super(context, dbname, factory, version);

    TableNames = tableNames;

    FieldNames = fieldNames;

    FieldTypes = fieldTypes;

  }



  @Override

  public void onCreate(SQLiteDatabase db)

  {

    if (TableNames == null)

    {

      message = NO_CREATE_TABLES;

      return;

    }



    for (int i = 0; i < TableNames.length; i++)

    {

      String sql = "CREATE TABLE " + TableNames[i] + " (";

      for (int j = 0; j < FieldNames[i].length; j++)

      {

        sql += FieldNames[i][j] + " " + FieldTypes[i][j] + ",";

      }

      sql = sql.substring(0, sql.length() - 1);

      sql += ")";

      db.execSQL(sql);

    }

  }



  @Override

  public void onUpgrade(SQLiteDatabase db, int arg1, int arg2)

  {

    for (int i = 0; i < TableNames[i].length(); i++)

    {

      String sql = "DROP TABLE IF EXISTS " + TableNames[i];

      db.execSQL(sql);

    }

    onCreate(db);

  }



  public void execSQL(String sql) throws java.sql.SQLException

  {

    SQLiteDatabase db = this.getWritableDatabase();

    db.execSQL(sql);

  }



  public Cursor select(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)

  {

    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);

    return cursor;

  }



  public long insert(String table, String fields[], String values[])

  {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues cv = new ContentValues();

    for (int i = 0; i < fields.length; i++)

    {

      cv.put(fields[i], values[i]);

    }

    return db.insert(table, null, cv);

  }



  public int delete(String table, String where, String[] whereValue)

  {

    SQLiteDatabase db = this.getWritableDatabase();



    return db.delete(table, where, whereValue);

  }



  public int update(String table, String updateFields[],

      String updateValues[], String where, String[] whereValue)

  {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues cv = new ContentValues();

    for (int i = 0; i < updateFields.length; i++)

    {

      cv.put(updateFields[i], updateValues[i]);

    }

    return db.update(table, cv, where, whereValue);

  }



  public String getMessage()

  {

    return message;

  }



  @Override

  public synchronized void close()

  {

    // TODO Auto-generated method stub

    super.close();

  }

}

沒有留言:

張貼留言