İlk: Sonra varlıklar app/aktifler
: db.sqlite Kopya varlıkları
- oluştur SqliteHelper.class klasör klasör oluşturma adı var
public class SqliteHelper SQLiteOpenHelper genişletir {
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.class içinde
- , yöntem isCreateDB oluşturun: "varlıktan veri/veri kopyalama verilerini/...."
public class MainActivity Aktivite {
@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;
}
}
Yanıt için teşekkürler ama db dosyamı varlık klasörüne kopyalamam gerektiğini söylüyorsunuz. Ben gerçekten bir db dosyasını bir url'den indirmek istiyorum – pithou