安卓:复制数据库从资源文件夹 [英] Android: Copying Database From Asset Folder

查看:161
本文介绍了安卓:复制数据库从资源文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想复制我的示例数据库从我的资产文件夹复制到/数据/数据​​/软件包名/数据库/目录中的应用程序中用到它。

我看了不少教程和其他解决方案,喜欢这里(<一href="http://stackoverflow.com/questions/10738623/copy-database-from-assets-folder-in-unrooted-device">Copy从无根设备资产文件夹数据库),并在这里(<一href="http://stackoverflow.com/questions/18805874/copy-database-from-assets-to-databases-folder">copy数据库从资产数据库文件夹),但它不是为我工作。我没有错误,但已复制数据库是空的。是不是有什么毛病我的编码?

下面是我的编码复制到数据库中。

  @覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    。getWindow()requestFeature(Window.FEATURE_ACTION_BAR);
    的setContentView(R.layout.activity_dictionary_type);

    文件DBFILE =新的文件(数据/数据​​/ com.example.myidictionary /数据库,DefinitionDB);

    如果(!dbfile.exists()){
        尝试 {
            copyDatabase(DBFILE);
        }赶上(IOException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }
        Toast.makeText(getApplicationContext(),样本数据被复制,Toast.LENGTH_LONG).show();
    }
    其他
        Toast.makeText(getApplicationContext(),数据库存在,Toast.LENGTH_LONG).show();

}

私人无效copyDatabase(文件DBFILE)抛出IOException异常
{
    InputStream的是= this.getAssets()开(DefinitionDB)。
    的OutputStream OS =新的FileOutputStream(DBFILE);

    byte []的缓冲区=新的字节[1024];

    而(is.read(缓冲液)大于0)
    {
        os.write(缓冲液);
    }

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

解决方案

尝试下面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.");
  }
  }

这篇关于安卓:复制数据库从资源文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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