简体   繁体   中英

import external db into app and use it in android

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?

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/

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();
         }
   }    
    }

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM