且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

安卓:复制数据库从资源文件夹

更新时间:2023-08-24 10:23:34

尝试下面code,让我知道是否它正常工作?

 公共类DataBaseWrapper扩展SQLiteOpenHelper
 {
  私有静态字符串变量= DataBaseWrapper.class.getName();
  私人字符串DB_PATH; // =/data/data/com.example.yourproject/databases/;
  私有静态字符串DB_NAME =Database.sqlite;
  私人SQLiteDatabase MyDatabase的= NULL;
  私人最终语境myContext;

  公共DataBaseWrapper(上下文的背景下)
  {
     超级(上下文,DB_NAME,空,1);

      this.myContext =背景;
      DB_PATH =/数据/数据​​/+ context.getPackageName()+/+数据库/;
      Log.v(log_tag,DBPATH:+ DB_PATH);
     //文件F = getDatabasePath(DB_NAME);
  }

  公共无效的CreateDatabase()抛出IOException异常{
   布尔dbExist = checkDataBase();
   如果(dbExist){
    Log.v(log_tag,数据库确实存在);
    }其他{
     Log.v(log_tag,数据库中不存在);
     this.getReadableDatabase();
     尝试 {
      copyDataBase();
        }赶上(IOException异常E){
      抛出新的错误(错误复制数据库);
      }
    }
   }

  私人无效copyDataBase()抛出IOException异常{
  InputStream的myInput = myContext.getAssets()开(DB_NAME)。
  字符串outFileName = DB_PATH + DB_NAME;
  的OutputStream myOutput =新的FileOutputStream(outFileName);
  byte []的缓冲区=新的字节[1024];
  INT长;
   而((长度= myInput.read(缓冲液))大于0){
    myOutput.write(缓冲液,0,长度);
   }
   myOutput.flush();
   myOutput.close();
   myInput.close();
  }

  私人布尔checkDataBase(){

     文件DBFILE =新的文件(DB_PATH + DB_NAME);
     //Log.v("dbFile,DBFILE ++ dbFile.exists());
     返回dbFile.exists();

 }

 公共布尔的openDatabase()抛出的SQLException
 {
    字符串的mpath = DB_PATH + DB_NAME;
    //Log.v("mPath的mpath);
    MyDatabase的= SQLiteDatabase.openDatabase(的mpath,空,SQLiteDatabase.CREATE_IF_NECESSARY);
    // mDataBase = SQLiteDatabase.openDatabase(的mpath,空,SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    返回MyDatabase的!= NULL;

 }


  @覆盖
  市民同步无效关闭()
  {
     如果(MyDatabase的!= NULL)
      myDataBase.close();
     super.close();
  }

 @覆盖
 公共无效的onCreate(SQLiteDatabase DB)
 {


  }

 @覆盖
 公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页)
 {
    Log.v(TAG,升级数据库,这将删除数据库并重新创建。);
  }
  }
 

I want to copy my sample database from my asset folder to the /data/data/packagename/databases/ directory to use it later in the application.

I have viewed many tutorial and other solution like here( Copy Database from assets folder in unrooted device) and here (copy database from assets to databases folder) but it not work for me. I have no error but the database that has been copied is empty. Is there something wrong with my coding?

Here is my coding for copying the database.

       @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    setContentView(R.layout.activity_dictionary_type);

    File dbfile=new File("data/data/com.example.myidictionary/databases","DefinitionDB");

    if (!dbfile.exists()) {
        try {
            copyDatabase(dbfile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Toast.makeText(getApplicationContext(), "Sample data is being copied", Toast.LENGTH_LONG).show();
    }
    else
        Toast.makeText(getApplicationContext(), "Database Exist", Toast.LENGTH_LONG).show();

}

private void copyDatabase(File dbFile) throws IOException 
{
    InputStream is = this.getAssets().open("DefinitionDB");
    OutputStream os = new FileOutputStream(dbFile);

    byte[] buffer = new byte[1024];

    while (is.read(buffer) > 0) 
    {
        os.write(buffer);
    }

    os.flush();
    os.close();
    is.close();
}

Try below code and let me know whether is it working properly?

 public class DataBaseWrapper extends SQLiteOpenHelper
 {
  private static String TAG = DataBaseWrapper.class.getName();
  private  String DB_PATH; //= "/data/data/com.example.yourproject/databases/";
  private static String DB_NAME = "Database.sqlite";
  private SQLiteDatabase myDataBase = null; 
  private final Context myContext;

  public DataBaseWrapper(Context context) 
  {
     super(context, DB_NAME, null, 1);

      this.myContext = context;
      DB_PATH="/data/data/" + context.getPackageName() + "/" + "databases/";
      Log.v("log_tag", "DBPath: " + DB_PATH);
     //  File f=getDatabasePath(DB_NAME);
  } 

  public void createDataBase() throws IOException{
   boolean dbExist = checkDataBase();
   if(dbExist){
    Log.v("log_tag", "database does exist");
    }else{
     Log.v("log_tag", "database does not exist");
     this.getReadableDatabase();
     try {
      copyDataBase();
        } catch (IOException e) {
      throw new Error("Error copying database");
      }
    }
   }

  private void copyDataBase() throws IOException{
  InputStream myInput = myContext.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);
   }
   myOutput.flush();
   myOutput.close();
   myInput.close();
  }

  private boolean checkDataBase(){

     File dbFile = new File(DB_PATH + DB_NAME); 
     //Log.v("dbFile", dbFile + "   "+ dbFile.exists()); 
     return dbFile.exists(); 

 }

 public boolean openDataBase() throws SQLException
 {
    String mPath = DB_PATH + DB_NAME; 
    //Log.v("mPath", mPath); 
    myDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY); 
    //mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); 
    return myDataBase != null; 

 }


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

 @Override
 public void onCreate(SQLiteDatabase db) 
 {


  }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
 {
    Log.v(TAG, "Upgrading database, this will drop database and recreate.");
  }
  }