2015-04-07 33 views
0

我有一个现有的数据库,我已经创建了我想用我的android应用程序。我已将该文件夹放入我的资产文件夹并具有DataBaseHelper.java文件。现在我想检索数据,然后在我的一个活动中显示数据,例如,以listView或其他任何方式显示数据。那么有人知道我该怎么做?接下来要做的是什么?如何在android中使用现有的数据库使用数据库帮助类

回答

0

这里有一些提示,让你走。

  • 运行在你的数据库文件的SQL语句:
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US'); 
INSERT INTO "android_metadata" VALUES ('en_US'); 
  • 将您的数据库(SQLite的文件,我假设)到资产/
  • 我会然后建议将您的应用程序中的文件复制到/data/data/your.package.name/databases/。下面是示例代码来做到这一点:
/** 
* Copies your database from your local assets-folder 
* to the just created empty database in the 
* system folder, from where it can be accessed and handled. 
* This is done by transfering bytestream. 
**/ 
private void copyDatabase() throws IOException{ 

    //Open your local db as the input stream 
    InputStream myInput = context.getAssets().open(DB_NAME); 

    // Path to the just created empty db 
    String outFileName = DB_PATH + DB_NAME; 

    //Open the empty db as the output stream 
    OutputStream myOutput = new FileOutputStream(outFileName); 

    //transfer bytes from the inputfile to the outputfile 
    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(); 
} 

然后,您可以打开DataBaseHelper所生成的文件。

+0

副本DB所以以后我跑,你把那里查询,那么我会说,除了表的Android _metadata,我已经有了吗?对于那个示例代码,我会把它放到哪个java文件中?我想把它放到DataBaseHelper.java文件中吗? –

+0

是的,Android需要android_metadata才能存在于DB文件中。是的,您可以将复制方法放入帮助程序中,并在用户首次安装应用程序时执行它(如果没有可用的数据库)。 –

+0

好的,那么一旦我这样做了,那么我怎样才能从数据库中使用查询获取数据,然后在我的应用程序的一个活动中显示一个列表视图,例如,你知道我该怎么做?这是我和我的团队成员无法解决的问题。 –

0

你可以试试下面的网址从资产

http://stackoverflow.com/questions/5945196/database-not-copying-from-assets