Pradhaban
Pradhaban

Reputation: 694

Android Database returns null

public class DBHelper extends SQLiteOpenHelper {

    private static  final int DB_VERSION=1;
    private static final String DB_NAME="SAMPLE.db";
    private static final String TABLE_NAME="events";
    private static final String KEY_ID="sampleId";
    private static final String KEY_TITLE="sampleTitle";
    private static final String KEY_DATE="sampleDATE";
    SQLiteDatabase dbEvents;


    public DBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS sampleTable(sampleID INTEGER PRIMARY KEY AUTOINCREMENT,sampleTitle TEXT,sampleDATE BIGINT,trash INTEGER DEFAULT 0) ");
        this.dbEvents=db;

    }

public Integer deleteItem(Integer itemId){
        Log.d("CURSOR:","IM HERE"+eventId);
        if(dbEvents == null){
            Log.d("CURSOR:","IM NOT INTIALIZING");
        }

        return null;
    }

Where I'm getting IM NOT INTIALIZING

and in my Activity I'm calling as [When Delete Button is clicked]

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dbHelper=new DBHelper(this);
} 
public void deleteItem(int Id){
    dbHelper=new DBHelper(this);
    dbHelper.deleteEvent(Id);
}

I cannot perform DB operation where it throws to Null Pointer Exception.

thanks in advance

Upvotes: 0

Views: 323

Answers (1)

ezcoding
ezcoding

Reputation: 2996

onCreate will be called, when you call getWritableDataBase() method with an instance of your DBHelper.

From the Javadocs for the method getWritableDataBase() with an instance of a class that extends SQLiteOpenHelper

Create and/or open a database that will be used for reading and writing. The first time this is called, the database will be opened and onCreate, onUpgrade and/or onOpen will be called.

This means, that this code

 @Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE IF NOT EXISTS sampleTable(sampleID INTEGER PRIMARY KEY AUTOINCREMENT,sampleTitle TEXT,sampleDATE BIGINT,trash INTEGER DEFAULT 0) ");
    this.dbEvents=db;

}

won't get you far. Since creating by calling getWritableDataBase or getReadableDataBase returns a SQLiteDatabase instance for performing SQLite operations.

So, from an Activity if you want to access your Database you have to do the following:

DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDataBase();
db.query("SELECT * FROM " + sampleTable);

Upvotes: 1

Related Questions