[英]Copy db from assets to db folder in device memory
I have tried to use a SQLite db by copying it from asset folder to device. 我试图通过将SQLite数据库从资产文件夹复制到设备来使用它。 I have also checked using DDMS if db is being copied or not.
我还使用DDMS检查了是否正在复制数据库。 Everything was fine but when I opened my copied db no tables were present inside it ie it was a blank db.
一切都很好,但是当我打开复制的数据库时,其中没有任何表,即它是空白数据库。
Please help me how to copy db along with its tables. 请帮助我如何复制数据库及其表。
This is my DBHelper class:- 这是我的DBHelper类:
public class DBHelper extends SQLiteOpenHelper {
private static String DB_NAME = "collegeDb2";
private SQLiteDatabase db;
private final Context context;
private String DB_PATH;
public DBHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException {
InputStream myInput = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public Cursor getColleges() {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
Cursor c = db.rawQuery("SELECT * FROM collegeslist", null);
// Note: colleges is the one table in External db. Here we trying to access the records of table from external db.
return c;
}
public Cursor getProducts() {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
Cursor d = db.rawQuery("SELECT * FROM productslist", null);
// Note: products is the one table in External db. Here we trying to access the records of table from external db.
return d;
}
@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
}
I am able to add tables using this code in onCreate()
:- 我可以在
onCreate()
使用此代码添加表:-
public void onCreate(SQLiteDatabase db) {
String CREATE_collegeslistTable = "CREATE TABLE collegeslist ( "
+ "_id INTEGER PRIMARY KEY NOT NULL ,Organization_Name VARCHAR DEFAULT (null) ,Organization_No VARCHAR DEFAULT (null) ,Assigned_To VARCHAR DEFAULT (null) ,Billing_Address VARCHAR DEFAULT (null) ,Billing_City VARCHAR DEFAULT (null) )";
db.execSQL(CREATE_collegeslistTable);
String CREATE_productslistTable = "CREATE TABLE productslist ( "
+ "_id INTEGER PRIMARY KEY NOT NULL ,Product_Name VARCHAR DEFAULT (null) ,Part_Number VARCHAR DEFAULT (null) ,Manufacturer VARCHAR DEFAULT (null) ,Product_Category VARCHAR DEFAULT (null) ,Vendor_Name VARCHAR DEFAULT (null), Unit_Price DOUBLE DEFAULT (null), Usage_Unit VARCHAR DEFAULT (null), Unit INTEGER DEFAULT (null) )";
db.execSQL(CREATE_productslistTable);
}
But this creates only two blank tables in db, I also want the data inside them. 但这在db中仅创建两个空白表,我也希望在其中包含数据。 As there are hundreds of entries in tables so I can not add them manually.
由于表中有数百个条目,因此我无法手动添加它们。
Please someone help.... 请有人帮助...。
You need to append the path of your db file in the database name: 您需要在数据库名称中附加db文件的路径:
private static String DB_NAME = "collegeDb2";
should be like: 应该是这样的:
private static String DB_NAME = "<path_where_you_are_copying_db>/collegeDb2.db";
Example: If you have copied your db file here: /storage/sdcard0/test.db
, then it should be: 示例:如果您已将数据库文件复制到
/storage/sdcard0/test.db
,则该文件应为:
private static String DB_NAME = "/storage/sdcard0/test.db"
Also you dont need your createDatabase()
method. 另外,您不需要
createDatabase()
方法。 As the database will be created automatically if it doesnt exists when it's super
is called 由于数据库将在
super
调用时不存在时自动创建
So finally I made it work by using the following DBHelper
class :- 所以最后我通过使用以下
DBHelper
类使其工作:-
public class DBHelper extends SQLiteOpenHelper {
public SQLiteDatabase database = null;
public File databaseFile;
public static String databaseName = "collegeDb.sqlite";
public String databasePath = "";
Context mContext;
public DBHelper(Context paramContext) {
super(paramContext, databaseName, null, 1);
this.mContext = paramContext;
Log.d("data", "package name:" + paramContext.getPackageName());
this.databasePath = ("data/data/" + paramContext.getPackageName() + "/databases/"+databaseName);
this.databaseFile = new File(this.databasePath);
if (!this.databaseFile.exists())
try {
deployDataBase(DBHelper.databaseName, this.databasePath);
return;
} catch (IOException localIOException) {
localIOException.printStackTrace();
}
}
private void deployDataBase(String dbNAme, String dbPath)
throws IOException {
InputStream localInputStream = this.mContext.getAssets().open(dbNAme);
FileOutputStream localFileOutputStream = new FileOutputStream(dbPath);
byte[] arrayOfByte = new byte[1024];
while (true) {
int i = localInputStream.read(arrayOfByte);
if (i <= 0) {
localFileOutputStream.flush();
localFileOutputStream.close();
localInputStream.close();
return;
}
localFileOutputStream.write(arrayOfByte, 0, i);
}
}
@Override
public synchronized void close() {
if (database != null)
database.close();
super.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
}
/**
* Getting all colleges
* returns list of colleges
* */
public List<String> getAllColleges(){
List<String> colleges = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM collegeslist";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
colleges.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning colleges
return colleges;
}
/**
* Getting all products
* returns list of products
* */
public List<String> getAllProducts(){
List<String> products = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM productslist";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
products.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning products
return products;
}
}
Thanks for your help friends. 感谢您的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.