Skip to content Skip to sidebar Skip to footer

How To Access And Query The Database That Is Copied To The Assets Folder?

I have read few tutorials where in a pre-existing database is copied to assets folder and write code for copying this database on to the default system path of the application data

Solution 1:

You need to copy your database file to application directory folder then use this file to open database

I use this to copyDatabase

privatevoidcopyDataBase()
{
    Log.i("Database", "New database is being copied to device!");
    byte[] buffer = newbyte[1024];
    OutputStream myOutput = null;
    int length;
    // Open your local db as the input stream
    InputStream myInput = null;
    try
    {
        myInput = myContext.getAssets().open(DB_NAME);
        // transfer bytes from the inputfile to the// outputfile
        myOutput = new FileOutputStream(DB_PATH + DB_NAME);
        while((length = myInput.read(buffer)) > 0)
        {
            myOutput.write(buffer, 0, length);
        }
        myOutput.close();
        myOutput.flush();
        myInput.close();
        Log.i("Database", "New database has been copied to device!");
        cmn.mailDetails();

    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
}

and

Open using this

protectedBoolean openDatabase()
{
    if(isDatabaseExist(false))
    {
        // Open the database
        String myPath = DB_PATH + DB_NAME;
        try
        {
            Log.i("Database", "Trying to Open Database!");
            if(myDataBase != null)
            {
                if(!myDataBase.isOpen())
                {
                    Log.i("Database", "Database is closed now opening it!");
                    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

                }
                else
                {
                    Log.i("Database", "Database is already Open!");
                }
                Log.i("Database", "Database is Opened successfully in OPEN_READWRITE  Mode !");
                returntrue;

            }
            else
            {
                myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
                Log.i("Database", "Database is Opened successfully in OPEN_READWRITE  Mode !");
                returntrue;
            }

        }
        catch(Exception e)
        {
            Log.e("Database", "Some error occured while opening Database Error:" + e.getMessage());
            myDataBase = null;
            returnfalse;
        }

    }
    else
    {
        copyDataBase();
    }
    returnfalse;
}

Post a Comment for "How To Access And Query The Database That Is Copied To The Assets Folder?"