2016-03-29 49 views
0

我已經使用SQLite資產助手成功實現了預填充數據庫,並使用此tutorial執行了一個查詢以列出表中對象的名稱。然而,我想向android應用程序添加CRUD函數來添加,刪除和插入新對象。我怎樣才能做到這一點?預填充的SQLite數據庫上的CRUD操作

DatabaseOpenHelper.java

import android.content.Context; 

import com.readystatesoftware.sqliteasset.SQLiteAssetHelper; 

public class DatabaseOpenHelper extends SQLiteAssetHelper { 
private static final String DATABASE_NAME = "camera1.db"; 
private static final int DATABASE_VERSION = 1; 

public DatabaseOpenHelper(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    } 


} 

DatabaseAccess.java

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

import java.util.ArrayList; 
import java.util.List; 

public class DatabaseAccess { 
private SQLiteOpenHelper openHelper; 
private SQLiteDatabase database; 
private static DatabaseAccess instance; 

/** 
* Private constructor to aboid object creation from outside classes. 
* 
* @param context 
*/ 
private DatabaseAccess(Context context) { 
    this.openHelper = new DatabaseOpenHelper(context); 
} 

/** 
* Return a singleton instance of DatabaseAccess. 
* 
* @param context the Context 
* @return the instance of DabaseAccess 
*/ 
public static DatabaseAccess getInstance(Context context) { 
    if (instance == null) { 
     instance = new DatabaseAccess(context); 
    } 
    return instance; 
} 

/** 
* Open the database connection. 
*/ 
public void open() { 
    this.database = openHelper.getWritableDatabase(); 
} 

/** 
* Close the database connection. 
*/ 
public void close() { 
    if (database != null) { 
     this.database.close(); 
    } 
} 

/** 
* Read all quotes from the database. 
* 
* @return a List of quotes 
*/ 
public List<String> getQuotes() { 
    List<String> list = new ArrayList<>(); 
    Cursor cursor = database.rawQuery("SELECT cameraname FROM camera", null); 
    cursor.moveToFirst(); 
    while (!cursor.isAfterLast()) { 
     list.add(cursor.getString(0)); 
     cursor.moveToNext(); 
    } 
    cursor.close(); 
    return list; 
} 
} 

回答

0

要做到這一點,你需要你的數據庫複製到設備:

private static void copyDatabase(Context context) throws IOException { 
    InputStream myInput = context.getResources().openRawResource(
      R.raw.database); 
    String outFileName = getFullDbName(context); 
    OutputStream myOutput = new FileOutputStream(outFileName); 

    byte[] buffer = new byte[1024]; 
    int length; 
    while ((length = myInput.read(buffer)) > 0) { 
     myOutput.write(buffer, 0, length); 
    } 
    myOutput.flush(); 
    myOutput.close(); 
    myInput.close(); 
} 

然後,只需打開數據庫通常:

mSqlite = new SqliteHelper(context, getFullDbName(context), null, 
      DATABASE_VERSION); 

之後,你可以寫任何你想要的原始查詢。

相關問題