The app that I'm developing has to read a TXT file from an SD card storage and display it in textview.
The process to get your file (any file) onto the emulator's pretend SD card is kind of tricky. First you have to create the SD card. I did this in eclipse by opening the AVD manager, selecting the device you want to create the SD card in and clicking edit.
In the edit screen, find the SD Card section and give your SD card a side. I gave mine 4 GB.
Then you have to move your file onto the SD card. In eclipse, this can be done by running your app and opening the DDMS view. Go to the File Explorer tab. Expand the "mnt" folder. Select the "sdcard" folder. Once selected, select the button in the upper right that has an image on a phone and an arrow. This should read "Push a file onto the device" when you hover over it. Click it. Find the file on your hard drive and push that baby onto the phone. Whew. Now its available to be read by our app.
Back to java. I pulled this code from someone's awesome answer on StackOverflow but forgot to bookmark it. Sorry!
// Find the directory for the SD Card using the API
// *Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
// Get the text file
File file = new File(sdcard, "filename.txt");
// Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
// You'll need to add proper error handling here
}
DialogDetails.setText(
text );
Friday, January 20, 2012
Friday, January 13, 2012
How to View Your Android App Database: SQLite Database Broswer
I've been using SQLite Database Browser to look through my android database and make changes. Linky link:
http://sourceforge.net/projects/sqlitebrowser/
You can pull your application's database off the emulator as a .sql file and open it up in this browser to see all that fancy sql stuff.
To get your database off the emulator:
First, you have to have eclipse open and running, and run your application in your emulator of choice.
Once the app is up and running, go back to eclipse and select Window > Open Perspective > DDMS
Under the Devices tab: Make sure the emulator that is running your app is highlighted/selected. Navigate to the "File Explorer" tab. (If it's not available, select Window > Show View > File Explorer.)
In the File Explorer tab: (1) open the "data" folder, (2) open a second "data" folder, (3) find and open the folder with "your application's name", (4) find and open the "databases" folder, (5) select the file with your application's name
In the upper right of the File Explorer frame, there is a button with an image of a floppy disk with an arrow. Click on the one that says "Pull a file from device" and save your database file somewhere memorable. It might automatically save it to your project's location on your hard drive.
Now you can view it and play around with it in SQLite Database Browser :)
Keep in mind that you have to upload the new database onto the phone or emulator before the changes can be accessed by your app.
Tuesday, July 5, 2011
Custom Tabs that Scroll Horizontally
So I designed horizontally scrolling tabs that use separate activities to fill the tab content. TI rate this a 1/5 on the fun scale: there are so many different files you have to create and different selection states you have to consider. (Click here for my update to this tutorial: Changing Tab with Horizontal Swipe Gesture)
tabhostlayout.xml - Pretty basic stuff here, if you followed the tab widget tutorial on the android dev site.[1] The only thing to note here is that I surrounded the tab widget with Horizontal Scroll View element to achieve a horizontal scroll for the tabs. (Note: Sorry for the formatting here. I've tried to fix it only to make it much much worse. Blame blogger?)
TabHostActivity.java - This activity must extend TabActivity. You will need to define the following variables and also set the divider drawable BEFORE setting up tabs
For each tab you would like to add, use the following code in onCreate:
After onCreate, you need to add two new classes. "setupTab" creates the tabs and tab content. "createTabView" handles all tab events, like setting the views for selection events and stuff like that.
tabs_bg.xml - In the code above, "createTabView" calls a layout called tabs_bg. Create this file in the layout folder. This layout creates the layout for each tab element. I have only added a single textview but an image view could also be added (but will need some adjustments to the java code not shown above). This is where some of the layout personalization comes in. Text size and style, and padding elements. Note the background and text color call drawable files that handle the color changes for selection events.
tab_bg_selector.xml - both bg and text selector drawable files require the same four states to be defined: active, pressed, selected (using arrows), and inactive. I don't really know why the text and bg have to be separate files, but when I tried to combine them, it wasn't displaying properly. This code resembles custom button selection.
tab_text_selector.xml
References:
1) http://developer.android.com/resources/tutorials/views/hello-tabwidget.html
2)http://joshclemm.com/blog/?p=136
For additional help, click here to download a zip containing all the files needed to create the above project.
![]() |
| Faded edges indicate additional content |
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</HorizontalScrollView>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" />
</LinearLayout>
</TabHost>
TabHostActivity.java - This activity must extend TabActivity. You will need to define the following variables and also set the divider drawable BEFORE setting up tabs
TabHost mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
Intent intent; // Reusable Intent for each tab
For each tab you would like to add, use the following code in onCreate:
intent = new Intent().setClass(TabHostActivity.this, PageOne.class);
setupTab(new TextView(this), "Tab One", intent);
After onCreate, you need to add two new classes. "setupTab" creates the tabs and tab content. "createTabView" handles all tab events, like setting the views for selection events and stuff like that.
private void setupTab(final View view, final String tag, final Intent myIntent) {
View tabview = createTabView(mTabHost.getContext(), tag);
TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(myIntent);
mTabHost.addTab(setContent);
}
private static View createTabView(final Context context, final String text) {
View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
TextView tv = (TextView) view.findViewById(R.id.tabsText);
tv.setText(text);
return view;
}
tabs_bg.xml - In the code above, "createTabView" calls a layout called tabs_bg. Create this file in the layout folder. This layout creates the layout for each tab element. I have only added a single textview but an image view could also be added (but will need some adjustments to the java code not shown above). This is where some of the layout personalization comes in. Text size and style, and padding elements. Note the background and text color call drawable files that handle the color changes for selection events.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabsLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/tab_bg_selector"
android:padding="3dip"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:textColor="@drawable/tab_text_selector"
android:gravity="center"
android:textSize="12dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/tabsText"
android:text="Title"
android:padding="10px">
</TextView>
</LinearLayout>
tab_bg_selector.xml - both bg and text selector drawable files require the same four states to be defined: active, pressed, selected (using arrows), and inactive. I don't really know why the text and bg have to be separate files, but when I tried to combine them, it wasn't displaying properly. This code resembles custom button selection.
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Active tab -->
<item
android:state_selected="true"
android:state_focused="false"
android:state_pressed="false">
<shape
android:shape="rectangle">
<gradient
android:startColor="#A8A8A8"
android:centerColor="#7F7F7F"
android:endColor="#696969"
android:angle="-90" />
</shape>
</item>
<!-- Inactive tab -->
<item
android:state_selected="false"
android:state_focused="false"
android:state_pressed="false">
<shape
android:shape="rectangle">
<gradient
android:startColor="#5C5C5C"
android:centerColor="#424242"
android:endColor="#222222"
android:angle="-90" />
</shape>
</item>
<!-- Pressed tab -->
<item
android:state_pressed="true"
android:drawable="@android:color/transparent" />
<!-- Selected tab (using d-pad) -->
<item
android:state_selected="true"
android:state_focused="true"
android:state_pressed="false"
android:drawable="@android:color/transparent" />
</selector>
tab_text_selector.xml
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:color="@android:color/white" />
<item
android:state_focused="true"
android:color="@android:color/white" />
<item
android:state_pressed="true"
android:color="@android:color/white" />
<item
android:color="#f8f8f8" />
</selector>
References:
1) http://developer.android.com/resources/tutorials/views/hello-tabwidget.html
2)http://joshclemm.com/blog/?p=136
For additional help, click here to download a zip containing all the files needed to create the above project.
Friday, July 1, 2011
Solution to "Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE"
Source: http://stackoverflow.com/questions/4709137/solution-android-install-failed-insufficient-storage-error
Getting this error:
[2011-07-01 10:36:22 - MDatHand] Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE
[2011-07-01 10:36:22 - MDatHand] Please check logcat output for more details.
[2011-07-01 10:36:22 - MDatHand] Launch canceled!
I used this solution:
RIGHT CLICK the root of your Android Project
SELECT "Run As" then go to "Run Configurations..."
LOCATE the "Android Application" node in the tree at the left then SELECT your project
SELECT "Target" tab on the right side of the window look down for the "Additional Emulator Command Line Options" field (sometimes you'll need to make the window larger)
PASTE "-partition-size 1024" there
CLICK "Apply" and then Run to use your emulator
Getting this error:
[2011-07-01 10:36:22 - MDatHand] Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE
[2011-07-01 10:36:22 - MDatHand] Please check logcat output for more details.
[2011-07-01 10:36:22 - MDatHand] Launch canceled!
I used this solution:
RIGHT CLICK the root of your Android Project
SELECT "Run As" then go to "Run Configurations..."
LOCATE the "Android Application" node in the tree at the left then SELECT your project
SELECT "Target" tab on the right side of the window look down for the "Additional Emulator Command Line Options" field (sometimes you'll need to make the window larger)
PASTE "-partition-size 1024" there
CLICK "Apply" and then Run to use your emulator
![]() |
| Like so. |
Thursday, June 23, 2011
“Debug certificate expired” Error in Eclipse
When there is no error in the code, but for some reason the project says there is an error and prevents you from running...
When you've torn your hair out trying to delete and re-import your project files to no avail...
When you've "cleaned" and "fixed project properties" so many times your index fingertip is bleeding...
Try looking at your project problems ( Window > Show View > Problems )
You might get something that looks like this:
Debug Certificate Expired...
If the above has happened to you, then I have a fix for you! You can probably solve this problem by deleting the debug certificate file. (Eclipse will then build a new one, and the error will go away.)
Win 7 OS: Go to ( Window > Preferences > Android > Build ) and find out where the debug.keystore file is located on your hard drive. Then using file explorer, find it and destroy it.
Thats it. Import your projects or whatever, do a clean and the error should disappear.
References:
http://stackoverflow.com/questions/2194808/debug-certificate-expired-error-in-eclipse-android-plugins
When you've torn your hair out trying to delete and re-import your project files to no avail...
When you've "cleaned" and "fixed project properties" so many times your index fingertip is bleeding...
Try looking at your project problems ( Window > Show View > Problems )
You might get something that looks like this:
Debug Certificate Expired...
If the above has happened to you, then I have a fix for you! You can probably solve this problem by deleting the debug certificate file. (Eclipse will then build a new one, and the error will go away.)
Win 7 OS: Go to ( Window > Preferences > Android > Build ) and find out where the debug.keystore file is located on your hard drive. Then using file explorer, find it and destroy it.
Thats it. Import your projects or whatever, do a clean and the error should disappear.
References:
http://stackoverflow.com/questions/2194808/debug-certificate-expired-error-in-eclipse-android-plugins
Wednesday, June 8, 2011
So you need to change the text size of simple_list_item_single_choice...
I feel you.
I tried for a month straight to call the checkedtextview in the android standard layout and resize the text. It never let me. I felt like a idiot. And now that I've figured it out, I know that it is more than just a feeling.
And so I'm posting it here, in the event that I actually forget how to do this later on. Because.. you know... I'm an idiot.
I went and copied the xml from the api demo and pasted it into a new .xml file(step 1). I accessed the text size and adjusted it thusly (step 2). Then I changed the java code to replace the simple_list_item_single_choice with my own custom row layout (step 3). Facepalmed for about two hours (step 4).
my_listitem_singlechoice.xml (i just chaged "textAppearance" attribute but I'm sure you can do other stuff to it too) :
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:textAppearance="?android:attr/textAppearanceSmall"
android:gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:paddingLeft="6dip"
android:paddingRight="6dip"
/>
my_java_with_singlechoice.java (this should look somewhat familiar) :
ListView lv = this.getListView();
MyListAdapter = new ArrayAdapter<String>(this, R.layout.my_listitem_singlechoice, myArrayList);
lv.setAdapter(MyListAdapter );
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
I tried for a month straight to call the checkedtextview in the android standard layout and resize the text. It never let me. I felt like a idiot. And now that I've figured it out, I know that it is more than just a feeling.
And so I'm posting it here, in the event that I actually forget how to do this later on. Because.. you know... I'm an idiot.
I went and copied the xml from the api demo and pasted it into a new .xml file(step 1). I accessed the text size and adjusted it thusly (step 2). Then I changed the java code to replace the simple_list_item_single_choice with my own custom row layout (step 3). Facepalmed for about two hours (step 4).
my_listitem_singlechoice.xml (i just chaged "textAppearance" attribute but I'm sure you can do other stuff to it too) :
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:textAppearance="?android:attr/textAppearanceSmall"
android:gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:paddingLeft="6dip"
android:paddingRight="6dip"
/>
my_java_with_singlechoice.java (this should look somewhat familiar) :
ListView lv = this.getListView();
MyListAdapter = new ArrayAdapter<String>(this, R.layout.my_listitem_singlechoice, myArrayList);
lv.setAdapter(MyListAdapter );
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
Wednesday, April 27, 2011
Getting Your Big Ass Database onto Your Android Phone
Yeah, I effing did it!!!!!!!!!! (Sorry, still pumped from finally getting this to work.)
First off: giving credit where credit is due. Many many many thanks to my sources:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
http://www.mail-archive.com/android-developers@googlegroups.com/msg28194.html
http://www.chriskopec.com/blog/2010/mar/13/deploying-android-apps-with-large-databases/
My project requires a preformed database (SQLite), which in total comes out to a whopping 17mb. Ridiculous I know, but my boss wants it all packaged with the app, and not just to be available online. Hypothetically, getting this to work should be as easy as creating a blank db and then copying the existing one over it from assets or raw. And this totally works-- if your db is smaller than 1mb. So I went and got some free file splitting software (http://www.dekabyte.com/filesplitter/) and split my db file into 1mb pieces. I put the pieces in the raw directory.
I created the DataBaseHelper class and made the necessary tweaks:
public class DataBaseHelper extends SQLiteOpenHelper {
// The Android's default system path of your application database.
private static final String DB_PATH = "/data/data/com.instacare/databases/";
private static final String DB_NAME = "MDAtHand";
private SQLiteDatabase myDataBase;
private final Context myContext;
Resources resources;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* @param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
// super(context, DB_NAME, null, 1);
resources = context.getResources();
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
copyDataBase();
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
// InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
// String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
// OutputStream myOutput = new FileOutputStream(outFileName);
// 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();
InputStream databaseInput = null;
// String outFileName = DB_PATH + DbConsts.DATABASE_NAME;
String outFileName = DB_PATH + DB_NAME;
OutputStream databaseOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
databaseInput = resources.openRawResource(R.raw.datafile01);
while ((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile02);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile03);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile04);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile05);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile06);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile07);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile08);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile09);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile10);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile11);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile12);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile13);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile14);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile15);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile16);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile17);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseOutput.flush();
databaseOutput.close();
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add your public helper methods to access and get content from the
// database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd
// be easy
// to you to create adapters for your views.
}
Then I added this awesomeness to the main.java file
DataBaseHelper myDbHelper = new DataBaseHelper(this);
//myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
Thats it :)
First off: giving credit where credit is due. Many many many thanks to my sources:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
http://www.mail-archive.com/android-developers@googlegroups.com/msg28194.html
http://www.chriskopec.com/blog/2010/mar/13/deploying-android-apps-with-large-databases/
My project requires a preformed database (SQLite), which in total comes out to a whopping 17mb. Ridiculous I know, but my boss wants it all packaged with the app, and not just to be available online. Hypothetically, getting this to work should be as easy as creating a blank db and then copying the existing one over it from assets or raw. And this totally works-- if your db is smaller than 1mb. So I went and got some free file splitting software (http://www.dekabyte.com/filesplitter/) and split my db file into 1mb pieces. I put the pieces in the raw directory.
I created the DataBaseHelper class and made the necessary tweaks:
public class DataBaseHelper extends SQLiteOpenHelper {
// The Android's default system path of your application database.
private static final String DB_PATH = "/data/data/com.instacare/databases/";
private static final String DB_NAME = "MDAtHand";
private SQLiteDatabase myDataBase;
private final Context myContext;
Resources resources;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* @param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
// super(context, DB_NAME, null, 1);
resources = context.getResources();
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
copyDataBase();
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
// InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
// String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
// OutputStream myOutput = new FileOutputStream(outFileName);
// 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();
InputStream databaseInput = null;
// String outFileName = DB_PATH + DbConsts.DATABASE_NAME;
String outFileName = DB_PATH + DB_NAME;
OutputStream databaseOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
databaseInput = resources.openRawResource(R.raw.datafile01);
while ((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile02);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile03);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile04);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile05);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile06);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile07);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile08);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile09);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile10);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile11);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile12);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile13);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile14);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile15);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile16);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseInput = resources.openRawResource(R.raw.datafile17);
while((length = databaseInput.read(buffer)) > 0) {
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseInput.close();
databaseOutput.flush();
databaseOutput.close();
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add your public helper methods to access and get content from the
// database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd
// be easy
// to you to create adapters for your views.
}
Then I added this awesomeness to the main.java file
DataBaseHelper myDbHelper = new DataBaseHelper(this);
//myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
Thats it :)
Subscribe to:
Comments (Atom)


