从资产复制分贝DB文件夹在设备内存 [英] Copy db from assets to db folder in device memory

查看:125
本文介绍了从资产复制分贝DB文件夹在设备内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试从资源文件夹将其拷贝到设备使用一个SQLite数据库。我一直在使用DDMS如果数据库正在被复制与否还检查。一切都很好,但是当我打开我的复制数据库没有表是它里面的present即它是一个空白的分贝。

I have tried to use a SQLite db by copying it from asset folder to device. I have also checked using DDMS if db is being copied or not. Everything was fine but when I opened my copied db no tables were present inside it i.e. it was a blank db.

请帮助我如何分贝其表一起复制。

这是我的DBHelper类: -

This is my DBHelper class:-

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 

}  

我能够加入的onCreate使用这种code表(): -

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);
 }  

但是,这将创建数据库只有两个空白的表,我也想在他们里面的数据。由于有数百个条目中的表,所以我不能手动添加。

请别人帮....

推荐答案

所以最后我做到了通过使用下面的 DBHelper 类工作: -

So finally I made it work by using the following DBHelper class :-

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;
 }
}

感谢您的帮助的朋友。

这篇关于从资产复制分贝DB文件夹在设备内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆