资产文件夹Android的外部数据库 [英] Android external database in assets folder

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

问题描述

我有一个Android应用程序,应该阅读并展开上的SQLite已经创建了一个数据库...它工作正常,在模拟器通过把数据库中的数据/数据​​/(包名)/库文件夹中的文件浏览器模拟器。现在的问题是发生在实机。显然,它没有数据库open.I试图把数据库的资产文件夹,但我没有得到与openhelper打开它。

I have an android application that is supposed to read and expand a database that is already created on sqlite...it works fine on emulator by putting database in "data/data/(packagename)/database" folder on the file explorer of emulator. Now problem is occuring with the real device. Obviously it doesnt have the database to open.I tried to put database in assets folder but I am not getting to open it with the openhelper.

推荐答案

你应该从你的资产目录.db文件复制到内部/外部存储。您可以使用下面codeS,

you should copy the .db file from your assets folder to an internal/external storage. You can use following codes,

private static String DB_PATH = "/data/data/your package/database/";  
private static String DB_NAME ="final.db";// Database name 

要创建一个数据库,

public void createDataBase() throws IOException 
{ 
  //If database not exists copy it from the assets 

   boolean mDataBaseExist = checkDataBase(); 
   if(!mDataBaseExist) 
   { 
      try  
      { 
        //Copy the database from assests 
        copyDataBase(); 
        Log.e(TAG, "createDatabase database created"); 
      }  
      catch (IOException mIOException)  
      { 
         throw new Error("ErrorCopyingDataBase"); 
     } 
  } 
} 

检查数据库中存在的位置:/数据/数据​​/软件包/数据库/ DB名称

Check that the database exists here: /data/data/your package/database/DB Name

private boolean checkDataBase() 
{ 
    File dbFile = new File(DB_PATH + DB_NAME); 
    return dbFile.exists(); 
} 

复制从资产数据库

Copy the database from assets

  private void copyDataBase() throws IOException 
  { 
    InputStream mInput = getApplicationContext().getAssets().open(DB_NAME); 
    String outFileName = DB_PATH + DB_NAME; 
    OutputStream mOutput = new FileOutputStream(outFileName); 
    byte[] mBuffer = new byte[1024]; 
    int mLength; 
    while ((mLength = mInput.read(mBuffer))>0) 
    { 
        mOutput.write(mBuffer, 0, mLength); 
    } 
    mOutput.flush(); 
    mOutput.close(); 
    mInput.close(); 
}

我希望它可以帮助你。

i hope it should help you.

这篇关于资产文件夹Android的外部数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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