2016-03-29 10 views
0

私はSQLite Asset Helperを使用してあらかじめデータベースを実装し、このtutorialを使用してテーブル内のオブジェクトの名前を一覧表示するクエリを実行しました。私は、アンドロイドアプリケーションに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); 

その後、必要な生のクエリを書き込むことができます。

関連する問題