简体   繁体   中英

Use a pre-built database in app in android phone

I have made an android app. I am using database in it. I have installed the .apk file on my phone and it works fine. But it does not show me any data I entered in database while I was on emulator. I need to use database tables filled previously. My database does not create on run time. How can I get the database on my phone to see app running perfectly fine with the database?

You can save your database file under assets or res/raw directory, on the app's first startup, copy that database file to /data/data/com.company.yourapp/databases/ , and open your database like usual.

The difference between saving files under assets and res/raw directories is that files under res/raw are compressed, while files under assets are not. And files under res/raw cannot exceed 1 MB before Android 2.3. So I'd suggest that you compress your database file yourself and save it to assets and in your code decompress the file using GZIPInputStream .

If you need your database out side the application for testing then i think you should export it into your sdcard.

public static void exportfile(String applicationPackageName,String databaseName,String pathOfFolder) throws FileNotFoundException, IOException
    {
                InputStream myInput;

                myInput = new FileInputStream("/data/data/"+applicationPackageName+"/databases/"+databaseName);

                File directory = new File("/sdcard"+pathOfFolder);

                if (!directory.exists()) 
                {
                    directory.mkdirs();
                } 

                OutputStream myOutput = new FileOutputStream(directory.getPath()+"/"+databaseName);

                byte[] buffer = new byte[1024];
                int length;
                while ((length = myInput.read(buffer))>0)
                {
                    myOutput.write(buffer, 0, length);
                }

                myOutput.flush();
                myOutput.close();
                myInput.close();

    }

applicationPackageName :- application package name

databaseName :- database file name

pathOfFolder :- path of folder where to export the file in sdcard

don't forget to add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in your manifest file.

And download any SQLite Manager to open that file.

Thanks.. hope it helps you.

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