Unable to copy SQLite database from assests folder to device memory

回眸只為那壹抹淺笑 提交于 2019-12-08 11:12:43

问题


I'm Unable to copy SQLite database from assests folder to device memory(trying on emulator).

I have a database in my project's assests folder which has a table containing 1000s of pre-existing rows.

I intend to copy the existing file from the assets folder into the database folder of emulator.

Piece of ACTIVITY

     @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

            //All views(list,textboxes) are declared.
    try {
        dbM = new DbManager(this);
        dbM.checkDataBase();

        try {
            dbM.createDataBase();
        } catch (Exception e) {
            throw new Error(" *** ERROR in DB Access *** " + e.getMessage());
        }

        dbM.openDB();
        symbolarr = dbM.getSymbol();

        lv.setAdapter(new ArrayAdapter<String>(this,
         android.R.layout.simple_list_item_1, symbolarr));
                } catch (Exception e) {
        throw new Error(" *** ERROR in onCreate *** " + e.getMessage());
    }

    finally {
        dbM.close();
    }
}

Piece of code from my DbManager class:

    public boolean checkDataBase() {

    String myPath = DATABASE_PATH + DATABASE_NAME;
    File f = new File(myPath);
    return f.exists();
}

public void createDataBase() {

    try {
        InputStream myInput = ctx.getAssets().open(DATABASE_NAME);
        OutputStream myOutput = new FileOutputStream(DATABASE_PATH
                + DATABASE_NAME);

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

    } catch (FileNotFoundException e) {
        throw new Error("file not found --  " + e.getMessage());
    } catch (IOException e) {
        throw new Error("io exception " + e.getMessage());
    } catch (Exception e) {
        throw new Error(" exception " + e.getMessage());
    }
}

public DbManager openDB() throws SQLException {
    dbmgr = new DbManager(ctx);
    mDb = dbmgr.getWritableDatabase();
    return this;
}

public String[] getSymbol() {
    Cursor cur;
    try {
        cur = mDb.rawQuery("select symbol,company_name from Scrip", null);
    } catch (SQLiteException e) {
        throw new Error(" *** ERROR in cursor *** " + e.getMessage());
    }

    String[] b1 = new String[1326];
    int x = 0;
    if (cur.moveToFirst()) {
        do {
            b1[x] = cur.getString(cur.getColumnIndex("symbol"));
            x++;
        } while (cur.moveToNext());
    }
    cur.close();
    return b1;
}

LOGCAT

    FATAL EXCEPTION: main


 java.lang.Error: file not found --  AndroidDB.db
    at com.dbexample.DbManager.createDataBase(DbManager.java:113)
    at com.dbexample.DataAttach.onCreate(DataAttach.java:83)
    at android.app.Activity.performCreate(Activity.java:4465)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
    at android.app.ActivityThread.access$600(ActivityThread.java:122)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4340)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    at dalvik.system.NativeStart.main(Native Method)

NOTE

1: Changing buffer size doesn't help..

2: There is a file named AndroidDB.db with size 62kb in my assets folder..

3: both the database names(in my assets folder and in my code) are same and I have android_metadata table in my DB which is in assets folder..

4: When I was not using createDataBase(), Database was getting created but my desired table i.e.Scrip was not getting copied. So when I tried to fetch the data from table, I was getting an exception that no such table Scrip.... That means I need to copy Scrip table from assets folder to database present on emulator memory. When I try to do the same using createDataBase(),I'm getting nullPointerException

5.: When I tried following code in createDatabase()

AssetManager assetManager = ctx.getAssets();
            String[] files = assetManager.list("Files");

            for (int i = 0; i < files.length; i++) {
                str[i] = "\n=" + " file=" + " :" + i + "=" + " name=" + "> "
                        + files[i];
            }
            Log.v("len=", "" + files.length);

Then files.length is equal to 0. That simply means It is unable to detect any files inside the assets folder.

ANY HELP WILL BE LIFE-SAVER !!!


回答1:


EDIT: Replace your code with this and let me know what happen, (This works fine in my case..)

DbManager.java class:

public class DbManager {
private DatabaseHelper dataHelper;
private SQLiteDatabase  mDb;
Context ctx;
String DATABASE_PATH = "/data/data/com.demo/databases/";
static String DATABASE_NAME="AndroidDB";

private static final int DATABASE_VERSION = 1;
DbManager(Context ctx)
{
    this.ctx = ctx;
    dataHelper = new DatabaseHelper(ctx);

}

private static class DatabaseHelper extends SQLiteOpenHelper {

    Context myContext = null;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.myContext = context;
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

        Log.w("DBHelper", "Upgrading database from version "
                        + oldVersion + " to " + newVersion
                        + ", which will destroy all old data");

        onCreate(db);

    }

}


   public boolean checkDataBase() {

        String myPath = DATABASE_PATH + DATABASE_NAME;
        File f = new File(myPath);
        return f.exists();
    }

    public void createDataBase() {

        openDB();            
        try {
            InputStream myInput = ctx.getAssets().open("AndroidDB.db");
            OutputStream myOutput = new FileOutputStream(DATABASE_PATH
                    + "AndroidDB");

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

            if (mDb.isOpen())
                mDb.close();
            myOutput.flush();
            myOutput.close();
            myInput.close();

        } catch (FileNotFoundException e) {
            throw new Error("file not found --  " + e.getMessage());
        } catch (IOException e) {
            throw new Error("io exception " + e.getMessage());
        } catch (Exception e) {
            throw new Error(" exception " + e.getMessage());
        }
    }

    public DbManager openDB() throws SQLException {

        mDb = dataHelper.getWritableDatabase();
        return this;
    }

    public String[] getSymbol() {
        Cursor cur;
        try {
            cur = mDb.rawQuery("select symbol,company_name from Scrip", null);
        } catch (SQLiteException e) {
            throw new Error(" *** ERROR in cursor *** " + e.getMessage());
        }

        String[] b1 = new String[1326];
        int x = 0;
        if (cur.moveToFirst()) {
            do {
                b1[x] = cur.getString(cur.getColumnIndex("symbol"));
                x++;
            } while (cur.moveToNext());
        }
        cur.close();
        return b1;
    }

    public void close() {
        try {
            mDb.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

 }

}



回答2:


Check if your added database name and one written in error is same ? (AndroidDB.db) also make sure you have android_metadata table in your database. :)




回答3:


Think that you can get the path from an existing db. So why don't ask Android to create the DB first?

try to do a "getWritableDb" before to copy your db. Then get the path thanks to "db.getPath()" and use this path to copy from assets.

That worked for me.



来源:https://stackoverflow.com/questions/8487085/unable-to-copy-sqlite-database-from-assests-folder-to-device-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!