开发者

use External database in android

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 h开发者_运维问答elp to me?


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


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.


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 .


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 */
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜