无法将 SQLite 数据库从资产文件夹复制到设备内存

发布于 2024-12-20 17:42:37 字数 4855 浏览 3 评论 0原文

我无法将 SQLite 数据库从assests 文件夹复制到设备内存(尝试在模拟器上)。

我的项目的 assets 文件夹中有一个数据库,其中有一个包含 1000 个预先存在的行的表。

我打算将现有文件从资产文件夹复制到模拟器的数据库文件夹中。

一段活动

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

我的 DbManager 类中的一段代码:

    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)

注意

1:更改缓冲区大小没有帮助..

2:有一个我的资产文件夹中名为 AndroidDB.db 的文件大小为 62kb。3

:两个数据库名称(在我的资产文件夹和我的代码中)相同,并且我的数据库中有 android_metadata 表,位于资产文件夹中。

4:当我没有使用createDataBase()时,数据库正在创建,但我想要的表 ieScrip 没有被复制。因此,当我尝试从表中获取数据时,我收到一个异常,no such table Scrip.... 这意味着我需要将 Scrip 表从资产文件夹复制到模拟器内存​​上的数据库。当我尝试使用 createDataBase() 执行相同操作时,我收到 nullPointerException

5.:当我尝试在 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);

时,files.length 等于 0 。这仅仅意味着它无法检测到资产文件夹内的任何文件。

任何帮助都将挽救生命!!!

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 !!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱她像谁 2024-12-27 17:42:37

编辑:用此替换您的代码并让我知道发生了什么,(这在我的情况下工作正常..)

DbManager.java类:

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

 }

}

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

 }

}
安稳善良 2024-12-27 17:42:37

检查一下你添加的数据库名称和写错的数据库名称是否相同? (AndroidDB.db)
还要确保数据库中有 android_metadata 表。 :)

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

酒绊 2024-12-27 17:42:37

认为您可以从现有数据库获取路径。那么为什么不让 Android 首先创建数据库呢?

在复制数据库之前尝试执行“getWritableDb”。然后通过“db.getPath()”获取路径并使用此路径从资产中复制。

这对我有用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文