我正在尝试在我的Android应用程序中DL .sqlite文件,存储它然后使用它。如果我理解正确,我首先需要从URL中对数据库进行DL,将其放在assets文件夹中,然后将其复制到:" / data / data / {package_name} / databases /"夹。 我找到了这个答案,帮助我从资产目录中复制数据库,但我仍然无法首先下载数据库。 Simple export and import of a SQLite database on Android
我在android dev中相当新,如果有人知道一步一步的教程或开源应用程序这样做会非常棒。
答案 0 :(得分:1)
要手动创建数据库,请使用Contract Android类。使用SQLiteBrowser在Android Studio中使用Monitor下载.sqlite文件以获取数据。
答案 1 :(得分:0)
首先:在app / assets中创建一个名称为 assets 的文件夹 然后:将 db.sqlite 复制到文件夹 资产
public class SqliteHelper扩展了SQLiteOpenHelper {
public static String DB_PATH = "/data/data/package.your.name/databases/";
private static String DB_NAME = "your_name_db.sqlite";
private final Context context;
public SqliteHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
}
/**
* copy database from assets to the device if not existed
**/
public boolean isCreatedDatabase() throws IOException {
// Default là đã có DB
boolean result = true;
// Nếu chưa tồn tại DB thì copy từ Asses vào Data
if (!checkExistDataBase()) {
this.getReadableDatabase();
try {
copyDataBase();
result = false;
} catch (Exception e) {
throw new Error("Error copying database");
}
// nó chưa tồn tại thì file sharedpreferences cũng chưa tồn tại tạo luôn
//isCreateSP();
}
return result;
}
/**
* check database exist on the device?
*/
private boolean checkExistDataBase() {
try {
String myPath = DB_PATH + DB_NAME;
File fileDB = new File(myPath);
if (fileDB.exists()) {
return true;
} else
return false;
} catch (Exception e) {
return false;
}
}
/**
* copy database from assets folder to the device
*
* @throws IOException
*/
private void copyDataBase() throws IOException {
InputStream myInput = context.getAssets().open(DB_NAME);
OutputStream myOutput = new FileOutputStream(DB_PATH + DB_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
公共类MainActivity扩展了Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
isCreateDB();
}
/*
* Copy db from asset vào database
*/
private boolean isCreateDB() {
SqliteHelper data = new SqliteHelper(this);
try {
return data.isCreatedDatabase();
} catch (IOException e) {
Toast.makeText(this, "Error copying database", Toast.LENGTH_LONG).show();
e.printStackTrace();
return false;
}
}