Loading the existing database in Android

advertisements

Possible Duplicate:
How to use an existing database with an Android application

I'm doing a project in Android, and i'm trying to load the existing database to my app. And i'm getting an error.

public class DBHelper extends SQLiteOpenHelper{

private static String DB_PATH = "/data/data/com.example.qbox/databases/";
private static String DB_NAME = "frases.db";

private SQLiteDatabase myDatabase;
private final Context _context;

public static final String KEY_ID = "_id";
public final static String KEY_FRASE = "frase";
public final static String KEY_AUTOR = "autor";
public final static String KEY_CATEGORIA = "categoria";
public final static String KEY_FAVORITA = "favorita";

public static final String DATABASE_TABLE = "frases";

private static final String[] cols = new String[] { KEY_ID, KEY_FRASE, KEY_AUTOR, KEY_CATEGORIA, KEY_FAVORITA};

public DBHelper(Context context) {

        super(context, DB_NAME, null, 1);
        this._context = context;
    }        

/**
* create new db and then rewrite records.
* */
public void createDataBase() throws IOException{

    boolean dbExist = checkDataBase();

    if(dbExist){
        // dn exists ... nothing to do
    } else {
      this.getReadableDatabase();
    try {

    copyDataBase();

    } catch (IOException e) {
    throw new Error("Error copiando Base de Datos");
    }
}

}

/**
* Check if db exists
*/
private boolean checkDataBase(){

SQLiteDatabase checkDB = null;

try{

String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

} catch(SQLiteException e) {

}
if(checkDB != null){

    checkDB.close();

}
return checkDB != null ? true : false;
}

/**
*  Copy Database
 **/
private void copyDataBase() throws IOException{

    InputStream myInput = _context.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    OutputStream myOutput = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while (( length = myInput.read(buffer)) > 0){
        myOutput.write(buffer, 0, length);
    }

    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void open() throws SQLException{
    try {
        createDataBase();
    } catch (IOException e) {
        throw new Error("Ha sido imposible crear la Base de Datos");
    }

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

}

/**
* INSERTAR NUEVA FRASE
* */
public long insertarFrase(Integer id,String frase, String autor, String categoria, String favorita ) {
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_ID, id);
    newValues.put(KEY_FRASE,frase);
    newValues.put(KEY_AUTOR, autor);
    newValues.put(KEY_CATEGORIA, categoria);
    newValues.put(KEY_FAVORITA, favorita);
    return myDatabase.insert(DATABASE_TABLE, null, newValues);
}

/**
* BORRAR FRASE CON _id = _rowIndex
* */
public boolean removerFrase(long _rowIndex) {
    return myDatabase.delete(DATABASE_TABLE, KEY_ID + "=" + _rowIndex, null) > 0;
}

/**
* ACTUALIZAR FRASE _id = _rowIndex
* */
public boolean updateFrase(Integer _rowIndex, String frase, String autor, String categoria, String favorita ) {
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_FRASE,frase);
    newValues.put(KEY_AUTOR, autor);
    newValues.put(KEY_CATEGORIA, categoria);
    newValues.put(KEY_FAVORITA, favorita);
    return myDatabase.update(DATABASE_TABLE, newValues, KEY_ID + "=" + _rowIndex, null) > 0;
}

  public List<Frase> getTodasLasFrases() {
        List<Frase> contacts = new ArrayList<Frase>();

        Cursor cursor = myDatabase.query(DBHelper.DATABASE_TABLE,
            cols, null, null, null, null, null);

        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
          Frase frase = cursorFrase(cursor);
          contacts.add(frase);
          cursor.moveToNext();
        }
        cursor.close();
        return contacts;
      }
  private Frase cursorFrase(Cursor cursor) {
      Frase frase = new Frase();
          frase.setId(cursor.getLong(0));
          frase.setFrase(cursor.getString(1));
          frase.setAutor(cursor.getString(2));
          frase.setCat(cursor.getString(3));
          frase.setFav(cursor.getString(4));
      return frase;
  }
  public Frase getContact(int id) {

        Cursor cursor = myDatabase.query(DBHelper.DATABASE_TABLE, cols, this.KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Frase frase = cursorFrase(cursor);

        return frase;
  }

}

in the main class

public class Home extends Activity implements OnClickListener {

ImageButton favBtn,catBtn,infoBtn,shareBtn;

DBHelper db;    

ListView lv;
List<Frase> values;
ArrayAdapter<Frase> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.home);

    favBtn =(ImageButton) findViewById(R.id.favBtn);
    catBtn = (ImageButton) findViewById(R.id.catBtn);
    infoBtn = (ImageButton) findViewById(R.id.infoBtn);
    shareBtn = (ImageButton) findViewById(R.id.shareBtn);

    infoBtn.setOnClickListener(this);
    catBtn.setOnClickListener(this);
    favBtn.setOnClickListener(this);
    shareBtn.setOnClickListener(this);
    prepararFrases();
}

@Override
public void onClick(View v) {

}

public void prepararFrases(){

    db.open();
      /*
    values = db.getTodasLasFrases();
    adapter = new ArrayAdapter<Frase>(this,
            android.R.layout.simple_list_item_1, values);

    //setListAdapter(adapter);

    for (Frase cn : values) {
        String log = "Id: "+cn.getId()+" ,Frase: " + cn.getFrase()+ " ,Autor: " + cn.getAutor();
        Log.d("Name: ", log);
    }  

    db.close();*/

}

}

The error:

11-10 21:45:08.366: E/AndroidRuntime(5535): Uncaught handler: thread main exiting due to uncaught exception
11-10 21:45:08.376: E/AndroidRuntime(5535): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.qbox/com.example.quotebox.Home}: java.lang.NullPointerException
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2503)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2519)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.ActivityThread.access$2200(ActivityThread.java:123)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1870)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.os.Looper.loop(Looper.java:123)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.ActivityThread.main(ActivityThread.java:4370)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at java.lang.reflect.Method.invokeNative(Native Method)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at java.lang.reflect.Method.invoke(Method.java:521)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at dalvik.system.NativeStart.main(Native Method)
11-10 21:45:08.376: E/AndroidRuntime(5535): Caused by: java.lang.NullPointerException
11-10 21:45:08.376: E/AndroidRuntime(5535):     at com.example.qbox.Home.prepararFrases(Home.java:74)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at com.example.qbox.Home.onCreate(Home.java:45)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-10 21:45:08.376: E/AndroidRuntime(5535):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2466)
11-10 21:45:08.376: E/AndroidRuntime(5535):     ... 11 more


You have a nullPointerException when you try to open db. You have declared it but you didn't create an instance of it. In the main activity in onCreate() method create a new instance of you DBHelper class and then pass a context to its constructor as an argument:

db = new DBHelper(getBaseContext());