How to have a default database
If you want to include a database with initial data in your apk, you have to insert the database file into the projects assets folder, then programmatically check if the database, and if it does not exists copy the one from the assets.
You will need a function to check if the database exists, fox example:
If the check shows that the the database does not exist, a function like this will copy it:
- // Open your local db as the input stream
- // Path to the just created empty db
- // transfer bytes from the inputfile to the outputfile
- byte[] buffer = new byte[1024];
- int length;
- while ((length = myInput.read(buffer)) > 0) {
- myOutput.write(buffer, 0, length);
- }
- // Close the streams
- myOutput.flush();
- myOutput.close();
- myInput.close();
- }
I usually use SQLiteOpenHelper, so I add the methods above to the SQLiteOpenHelper class, and use the following code to open the database:
- try{
- mDbHelper = new DatabaseHelper(mContext);
- boolean isExist = mDbHelper.isDataBaseExist();
- if(!mDbHelper.isDataBaseExist()){
- //get database, we will override it in next steep
- //but folders containing the database are created
- mDb = mDbHelper.getWritableDatabase();
- mDb.close();
- //copy database
- mDbHelper.copyDataBase();
- }
- mDb = mDbHelper.getWritableDatabase();
- Log.e("log_tag","Can not open database");
- }
- Log.e("log_tag","Can not copy initial database");
- }
As you can see each method handles the database as a general file, so it can be used for any file you want to have a default "value" in your application.
New tutorials from Helloandroid
Recent Apps
Android on Twitter
-
@StephanieNich10 (Stephanie Nichols)#android I laughed so hard at ochocinco 's avi. Hahahaha http://t.co/MPuhhi3m
26 weeks 1 day ago -
@CarlaAtkins8 (Carla Atkins)#android Omg! This is actually f'n interesting http://t.co/JodMOehr
26 weeks 1 day ago -
@MarianMcleod12 (Marian Mcleod)#android Precisely what song is? http://t.co/YmJXU0rB
26 weeks 1 day ago -
@JoBeach15 (Jo Beach)#android haha this made me laugh, i love ted:-) http://t.co/gtcWQ79C
26 weeks 1 day ago -
@aochart3 (青ちゃ)Start playing Paradise Island on Android http://t.co/DEID0Ao5 #Android #Androidgames #Gameinsight http://t.co/e1bifSeL
26 weeks 1 day ago
Poll
Useful resources
Android Development Projects
- FreeLance Android developer by shadyahmed84
- Android mobile App Development by appsoftexpert
- Social Networking Mobile App by ziptieapp
- Iphone/Android work project Beta 1 by Tokks
- una presentacion (propaganda) para un seminario virtual para importadores que recien se inician en el mercado peruano by petityo
- iphone ipad app - repost by dreamaginat
- Anroid Expert needed for making 2 version of apk from existing code and features by milliondollarmil
- Build me a Very Complex iPhone/iPad App - repost by fallinddfallindd
- program for an APP by majorpain515
- Built Website and mobile app by ADICTUA1



