gpt4 book ai didi

android - 如何将已构建的数据库导入到Android应用程序

转载 作者:行者123 更新时间:2023-11-29 01:53:08 24 4
gpt4 key购买 nike

我是 android 的新手,我必须构建一个 android 应用程序,这将是一个测验,在此我每次都必须从给定的表中选择随机问题。我已经建立了一个数据库,任何人都可以帮助我如何导入它到我的应用程序。我将使用一个 Intent ,该 Intent 每次都会调用相同的 Activity ,并且每次在 Activity 中随机编号。生成后它会检查它是否较早生成,如果不是则它会从数据库中选择问题。

也欢迎任何其他关于实现从数据库检索问题或实现此应用程序的建议。

最佳答案

正如@rwilliams 所说,您可以将数据库从 Assets 复制到应用程序目录。您只需要检查您是否已经复制了它。

这是我的做法。

只需将您的数据库放在 Assets 目录中即可。

public class DatabaseHelper extends SQLiteOpenHelper {

public static String DB_PATH = "/data/data/com.aavid.advance.alarm.clock/databases/";
private String dbName = "world_time.db";
protected SQLiteDatabase theDatabase;
private final Context context;

public DatabaseHelper(Context c, String dbName){
super(c,dbName, null, 1);
this.dbName = dbName;
this.context = c;
}

public void createDataBase() throws IOException{

boolean dbExist = checkDataBase();

if(dbExist){
//do nothing - database already exist
}else{
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}

private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String path = DB_PATH + dbName;
checkDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException{

File f = new File(DB_PATH);
f.mkdirs();

InputStream myInput = context.getAssets().open(dbName);
String outFileName = DB_PATH + dbName;
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();
}

public void openDataBase() throws SQLException{
String myPath = DB_PATH + dbName;
theDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY|SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}

@Override
public synchronized void close() {
if(theDatabase != null)
theDatabase.close();
super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

关于android - 如何将已构建的数据库导入到Android应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16770001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com