use External database in android

时光总嘲笑我的痴心妄想 提交于 2019-12-08 06:42:40

问题


I have created database AddressBookMaster.db using Sqlite Browser and also create table AddressBook in mentioned database. But now problem is that I want to use this .db file in my application so where should I put this db file and how to fetch in application?

Is there any example or tutorial which can help to me?


回答1:


The information contained in Using your own SQLite database in Android applications should have exactly what you are looking for.

You should note that while this is not really difficult it is not just a set of trivial commands that would be done outside of your application.




回答2:


You can put your Database file in the SDcard also. Use following code to use the Database from the SDCard.

File dbfile = new File("/sdcard/Your_db_File.db" ); 
SQLiteDatabase  db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);



回答3:


The information contained in "Using your own SQLite database in Android applications" is very userful for U and If U have db with more than 1024 bytes size then first split db into small parts and copy that all small dbs in your application dirrectory .




回答4:


Use android-sqlite-asset-helper, to fill (initialize) the database of your app on installation

If You want to change the default folder of the database to sdcard:

public class MyApplication extends Application {

    @Override
    public void onCreate() {

        SQLiteOpenHelper helper = ..
        SQLiteDatabase db = helper.getWritableDatabase()
    }


    @Override
    public File getDatabasePath(String name) {
        return new File(getDatabasePathString(name));
    }

    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
        return super.openOrCreateDatabase(getDatabasePathString(name), mode, factory);
    }

    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
        return super.openOrCreateDatabase(getDatabasePathString(name), mode, factory, errorHandler);
    }

    /*Put the default folder to store database of your application / or activity here */
    public String getDatabasePathString(String name) {
        return getExternalCacheDir()+ "/" + name+".db";  /* /storage/emulated/0/Android/data/com.my.app/cache */
    }

}


来源:https://stackoverflow.com/questions/5360166/use-external-database-in-android

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