我已經在我正在導入到我的android應用程序的sqlite工作室中創建數據庫。 SQLite的助手代碼如下:從sqlite數據庫的物理副本創建數據庫時SQL(查詢)錯誤或缺少數據庫
public class DatabaseHelper extends SQLiteOpenHelper {
String DB_PATH = null;
private static String DB_NAME = "mydatabases";
private static SQLiteDatabase myDataBase;
private final Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 21);
this.myContext = context;
this.DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
Log.e("Path 1", DB_PATH);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[10];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
catch(IOException ex){}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion){
try {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[10];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
現在我想獲取從數據庫中的數據,下面是代碼在活動負荷檢索數據:
onActivityCreated代碼:
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
final ArrayList<String> strArary;
myDbHelper = new DatabaseHelper(getActivity());
c = myDbHelper.getReadableDatabase().rawQuery("SELECT * FROM categories",null) ; // myDbHelper.query("categories",null,null,null,null,null,null);
if (c.moveToFirst()) {
do {
strArary1.add(c.getString(0));
strArary.add(c.getString(1));
} while (c.moveToNext());
}
定的代碼加薪題目中提到的一些錯誤。
請幫我解決問題。
考慮使用[sqlite的資產輔助(https://github.com/jgilfelt/android-sqlite-asset-helper)來代替。 – laalto
我認爲你需要在'onCreate'之前這麼做,因爲只有當文件不存在時才調用onCreate',這種情況下數據庫文件被創建,然後調用'onCreate'中的代碼。 – MikeT