import external db into app and use it in android

2019-04-14 16:43发布

问题:

Im new to android development. Now im trying to use sqlite db. I created a database sqlite file using sqlite manager. I imported it to the project by /data/data/packagename/dbname, it works fine in emulator , but if I took release in device the app crashes,I didnt know what happens and why it happens. Any Suggestions for it?

回答1:

You cannot use a External DB in that manner. When you import it into your project it doesn't mean it is available in all devices from there after(Assuming you used DDMS for this). It means that DB is available to that particular emulator only. Follow the below link to find out how to add a External DB to your Application..

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/



回答2:

private void StoreDatabase() {
     File DbFile=new File("data/data/packagename/DBName.sqlite");
     if(DbFile.exists())
     {
         System.out.println("file already exist ,No need to Create");
     }
     else
     {
         try 
         {
             DbFile.createNewFile();
             System.out.println("File Created successfully");
             InputStream is = this.getAssets().open("DBName.sqlite");
             FileOutputStream fos = new FileOutputStream(DbFile);
             byte[] buffer = new byte[1024];
                int length=0;
                while ((length = is.read(buffer))>0)
                {
                fos.write(buffer, 0, length);
                }
             System.out.println("File succesfully placed on sdcard");
                //Close the streams
                fos.flush();
                fos.close();
                is.close();
         }
         catch (IOException e)
         {
             e.printStackTrace();
         }
   }    
    }


回答3:

View this link, this will be very helpful if you are using your own database in Android.

http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

in this tutorial you have to put your database in assets folder of your project and the database will automatically transferred to database folder of you device.



回答4:

See https://github.com/jgilfelt/android-sqlite-asset-helper for a helper lib to take care of this.

(I haven't used this library personally but I came across it yesterday while searching for something else. It appears to do what you need, though).