NSouth
NSouth

Reputation: 5276

How do I save a SQLite database with the .db extension?

Super beginner here.

I've created a SQLite database and I want to view it with the SQLiteManager plugin, but my database doesn't add the .db extension on my (virtual) device. So far I've had to copy the file to my computer, change the extension, and push it back in order for the SQLiteManager icon to enable. Then I can see the database.

How can I avoid this run-around?

Also, someone mentioned I shouldn't rely on "/data/data/" to be the correct path. They suggested I use Context.openOrCreateDatabase or one of the get*Path or get*Dir methods. Could someone elaborate on these? The code I used is from a Youtube tutorial I saw.

Here's the code that defines the path:

try {
        String destPath = "/data/data/" + getPackageName() + "/databases/GradesDB.db";
        File f = new File(destPath);
        if(!f.exists()) {
            CopyDB( getBaseContext().getAssets().open("mydb"),
                new FileOutputStream(destPath));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Upvotes: 0

Views: 1603

Answers (4)

Farido mastr
Farido mastr

Reputation: 504

I know it's late

First at all use this dependency

    compile 'com.ajts.androidmads.sqliteimpex:library:1.0.0'

and use this code to export the database

public static boolean exportDb(Context context, String databaseName) {

        File dbDir = new File(Environment.getExternalStorageDirectory(),"your_path");
        if (!dbDir.exists())
        {
            dbDir.mkdirs();
        }

        SQLiteImporterExporter sqLiteImporterExporter = new SQLiteImporterExporter(context, databaseName);
        try {
            sqLiteImporterExporter.exportDataBase(Environment.getExternalStorageDirectory()+"your_path");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;

    }

Upvotes: 1

Axe
Axe

Reputation: 65

I agree with I1nuxuser. Here is another reference: https://github.com/jgilfelt/android-sqlite-asset-helper

Upvotes: 0

Jorge Alfaro
Jorge Alfaro

Reputation: 924

You should not rely on "data/data" because it may change or it may not work on some devices, getDatabasePath (String name) will always return the correct path, the documentation says

Returns the absolute path on the filesystem where a database created with openOrCreateDatabase

Upvotes: 3

l1nuxuser
l1nuxuser

Reputation: 333

this is not the right way to work on data base on android use this guide to create a dbhelper

guide

and after this you can make the db file name whatever you like

Upvotes: 1

Related Questions