1. Download our Official Android App: Forums for Android!

Apps Use my own database

Discussion in 'Android Development' started by farfrumsober, Jun 6, 2011.

  1. farfrumsober

    farfrumsober Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    3
    Joined:
    Jun 21, 2010

    Jun 21, 2010
    3
    0
    5
    Is there a way that I can use my own database when creating an app?

    What I mean by that is that I want the app to start with a database already loaded so one doesnt have to be created when the app is started?
     

    Advertisement

  2. JiMMaR

    JiMMaR Android Enthusiast
    Rank:
    None
    Points:
    53
    Posts:
    363
    Joined:
    Jun 12, 2010

    Jun 12, 2010
    363
    57
    53
  3. farfrumsober

    farfrumsober Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    3
    Joined:
    Jun 21, 2010

    Jun 21, 2010
    3
    0
    5
    Thanks, but I have tried that already. For the life of me I cant get it to work. Im sure it is some error on my end, but I cant figure out where.

    When I try to test it, I just get a force close in my emulator.
     
  4. JiMMaR

    JiMMaR Android Enthusiast
    Rank:
    None
    Points:
    53
    Posts:
    363
    Joined:
    Jun 12, 2010

    Jun 12, 2010
    363
    57
    53
    you should be able to determine what causes the crash from DDMS logcat, also you can try and debug your app [with break points] to see what's exactly going on
     
  5. zahidiqbal1990

    Rank:
    None
    Points:
    25
    Posts:
    8
    Joined:
    Oct 11, 2011

    Oct 11, 2011
    8
    0
    25
    I have also used it is also giving me force closed can anyone told me why it is giving me this kind of error???? I cannot know from log cat
     
  6. jiminaus

    jiminaus Well-Known Member
    Rank:
    None
    Points:
    63
    Posts:
    190
    Joined:
    Oct 27, 2011

    Oct 27, 2011
    190
    36
    63
    Sydney, Australia
    Without specific details we cannot help you; except to tell you that an application is forced closed by an unhandled exception. This unhandled exception is logged to logcat.

    Please either post the exception trace or post the relevant code with a description of how you can reliably reproduce the force close.
     
  7. odhran

    odhran Newbie
    Rank:
    None
    Points:
    35
    Posts:
    11
    Joined:
    Jan 16, 2012

    Hi farfrumsober,

    I was working on the exact same thing last night!lol

    JiMMaR has given you an excellent link - thats the same site I used. Although I discovered through hours of working with the example that it wasn't perfect.

    Below is the code which works for me (I am a newbie, but I hope it's to a reasonable standard!). Please go through it and compare it to your code and hopefully you'll be able to get it working.

    Main.java
    Code (Text):
    1. package com.odhranlynch.interiordesigner;
    2.  
    3. import com.odhranlynch.interiordesigner.R;
    4.  
    5. import java.io.IOException;
    6.  
    7. import android.app.Activity;
    8. import android.database.Cursor;
    9. import android.database.SQLException;
    10. import android.os.Bundle;
    11. import android.widget.Toast;
    12.  
    13. public class Main extends Activity {
    14.     /** Called when the activity is first created. */
    15.     @Override
    16.     public void onCreate(Bundle savedInstanceState) {
    17.         super.onCreate(savedInstanceState);
    18.         setContentView(R.layout.main);
    19.         DataBaseHelper myDbHelper = new DataBaseHelper(this);;
    20.         myDbHelper = new DataBaseHelper(this);
    21.        
    22.         //Load "productDatabase" database (see assets to left).
    23.         {
    24.             try {
    25.                 myDbHelper.createDataBase();}
    26.             catch (IOException ioe) {
    27.                 throw new Error("Unable to create database");}
    28.        
    29.             try {
    30.                 myDbHelper.openDataBase();}
    31.             catch(SQLException sqle){
    32.                 throw sqle;}
    33.     }
    34.    
    35.   //---get all titles---
    36.     myDbHelper.openDataBase();
    37.     Cursor cursorPosition = myDbHelper.getAllTitles();
    38.    
    39.     if (cursorPosition.moveToFirst())
    40.     {
    41.     do {
    42.     DisplayTitle(cursorPosition);
    43.     } while (cursorPosition.moveToNext());
    44.     }
    45.     myDbHelper.close();
    46.     }
    47.  
    48.     public void DisplayTitle(Cursor cursorPosition)
    49.     {
    50.         Toast.makeText(this,
    51.         "id: " + cursorPosition.getString(0) + "\n" +
    52.         "TITLE: " + cursorPosition.getString(1) + "\n" +
    53.         "CATEGORY: " + cursorPosition.getString(2) + "\n" +
    54.         "BODY: " + cursorPosition.getString(3),
    55.         Toast.LENGTH_LONG).show();}
    56. }
    DataBaseHelper.java
    Code (Text):
    1. package com.odhranlynch.interiordesigner;
    2.  
    3. import java.io.FileOutputStream;
    4. import java.io.IOException;
    5. import java.io.InputStream;
    6. import java.io.OutputStream;
    7.  
    8. import android.content.Context;
    9. import android.database.Cursor;
    10. import android.database.SQLException;
    11. import android.database.sqlite.SQLiteDatabase;
    12. import android.database.sqlite.SQLiteException;
    13. import android.database.sqlite.SQLiteOpenHelper;
    14.  
    15. public class DataBaseHelper extends SQLiteOpenHelper{
    16.  
    17.     //The Android's default system path of your application database.
    18.     private static String DB_PATH = "/data/data/com.odhranlynch.interiordesigner/databases/";
    19.     private static String DB_NAME = "productDatabase";
    20.     public static final String KEY_ROWID = "_id";
    21.     public static final String KEY_TITLE = "title";
    22.     public static final String KEY_CATEGORY = "category";
    23.     public static final String KEY_BODY = "body";
    24.     private SQLiteDatabase myDataBase;
    25.     final Context myContext;
    26.  
    27.     /**
    28.      * Constructor
    29.      * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
    30.      * @param context
    31.      */
    32.     public DataBaseHelper(Context context) {
    33.  
    34.         super(context, DB_NAME, null, 1);
    35.         this.myContext = context;
    36.     }  
    37.  
    38.   /**
    39.      * Creates a empty database on the system and rewrites it with your own database.
    40.      * */
    41.     public void createDataBase() throws IOException{
    42.  
    43.         boolean dbExist = checkDataBase();
    44.  
    45.         if(dbExist){
    46.             //do nothing - database already exist
    47.         }else{
    48.  
    49.             //By calling this method and empty database will be created into the default system path
    50.                //of your application so we are gonna be able to overwrite that database with our database.
    51.             this.getReadableDatabase();
    52.  
    53.             try {
    54.                 this.close();
    55.                 copyDataBase();
    56.  
    57.             } catch (IOException e) {
    58.  
    59.                 throw new Error("Error copying database");
    60.  
    61.             }
    62.         }
    63.  
    64.     }
    65.  
    66.     /**
    67.      * Check if the database already exist to avoid re-copying the file each time you open the application.
    68.      * @return true if it exists, false if it doesn't
    69.      */
    70.     private boolean checkDataBase(){
    71.  
    72.         SQLiteDatabase checkDB = null;
    73.  
    74.         try{
    75.             String myPath = DB_PATH + DB_NAME;
    76.             checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    77.  
    78.         }catch(SQLiteException e){
    79.  
    80.             //database does't exist yet.
    81.  
    82.         }
    83.  
    84.         if(checkDB != null){
    85.  
    86.             checkDB.close();
    87.  
    88.         }
    89.  
    90.         return checkDB != null ? true : false;
    91.     }
    92.  
    93.     /**
    94.      * Copies your database from your local assets-folder to the just created empty database in the
    95.      * system folder, from where it can be accessed and handled.
    96.      * This is done by transfering bytestream.
    97.      * */
    98.     private void copyDataBase() throws IOException{
    99.  
    100.         //Open your local db as the input stream
    101.         InputStream myInput = myContext.getAssets().open(DB_NAME);
    102.  
    103.         // Path to the just created empty db
    104.         String outFileName = DB_PATH + DB_NAME;
    105.  
    106.         //Open the empty db as the output stream
    107.         OutputStream myOutput = new FileOutputStream(outFileName);
    108.  
    109.         //transfer bytes from the inputfile to the outputfile
    110.         byte[] buffer = new byte[1024];
    111.         int length;
    112.         while ((length = myInput.read(buffer))>0){
    113.             myOutput.write(buffer, 0, length);
    114.         }
    115.  
    116.         //Close the streams
    117.         myOutput.flush();
    118.         myOutput.close();
    119.         myInput.close();
    120.  
    121.     }
    122.  
    123.     public void openDataBase() throws SQLException{
    124.  
    125.         //Open the database
    126.         String myPath = DB_PATH + DB_NAME;
    127.         myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    128.     }
    129.  
    130.     @Override
    131.     public synchronized void close() {
    132.  
    133.             if(myDataBase != null)
    134.                 myDataBase.close();
    135.  
    136.             super.close();
    137.  
    138.     }
    139.  
    140.     @Override
    141.     public void onCreate(SQLiteDatabase db) {
    142.  
    143.     }
    144.  
    145.     @Override
    146.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    147.  
    148.     }
    149.  
    150.     public Cursor getAllTitles()
    151.     {
    152.     return myDataBase.query("product", new String[] {
    153.     KEY_ROWID,
    154.     KEY_TITLE,
    155.     KEY_CATEGORY,
    156.     KEY_BODY},
    157.     null,
    158.     null,
    159.     null,
    160.     null,
    161.     null);
    162.     }
    163.         // Add your public helper methods to access and get content from the database.
    164.        // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
    165.        // to you to create adapters for your views.
    166.  
    167. }

    JiMMaR and jiminau have mentioned logcat in their replies. I found it very useful in solving my issues trying to connect to a database. I would certainly recommend you get familiar with it as best you can.

    If you have no luck, post your logcat details here :)
     
  8. Sam Voss

    Sam Voss Android Enthusiast
    Rank:
    None
    Points:
    43
    Posts:
    367
    Joined:
    Jun 25, 2010

    Jun 25, 2010
    367
    44
    43
    Programmer, in school
    Wisconsin
    as odhran had stated, thats nearly EXACTLY how I do it, I have a preloaded database into TextSecretary and is ran just like that, however with a few more get and set methods for adding new away messages and getting what the actual message was.

    I'm sorry but there really aren't a ton of GOOD guides on SQLite out there, I've been meaning to get around to making one, but I need to finish this update on Ultimath first.

    If you have any questions on that code, let us know I will be sure to answer any questions you may have.
     

Share This Page

Loading...