04 September 2010
android create db on sdcard

把DB建立在SD Card上其實很簡單。

先建立一個有關db操作的class,

注意,此範例尚無新增、查詢等method,將在下一篇介紹如何新增、查詢

此範例單純只有在sd card建立sqlite datebase

如下

public class db_sample {
public static final String STR_TABLE_NAME = "table_name"; //table名稱
public static final String STR_FIELD_ID = "field_id"; //欄位名稱
public static final String STR_FIELD_NAME = "field_name"; //欄位名稱
private static Context context;

public db_sample(Context context) {
this.context = context; //new這個class時,一定要傳入context,因為openOrCreateDatabase是由context底下的method
}

//建立table的method
public static final void fnCreateDB(){
//MODE_WORLD_WRITEABLE,只能有寫的權限
SQLiteDatabase dbwrite
= context.openOrCreateDatabase("/sdcard/hi_test.db", context.MODE_WORLD_WRITEABLE, null);

//建立table
String sql =
String.format("CREATE TABLE %s (%s INTEGER primary key autoincrement, %s text )"
, STR_TABLE_NAME
, STR_FIELD_ID
, STR_FIELD_NAME
);
dbwrite.execSQL(sql);
}


}




接著就在需要的地方呼叫即可~

public class test extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db_sample db = new db_sample(this);
db.fnCreateDB();

}

}




blog comments powered by Disqus