I have extended SQLiteOpenHelper in this one class and have used the following method to update my database.
public void UpDateDataBase(ItemClass itemClass){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_ItemClass_NAME, itemClass.getTaskName());
contentValues.put(KEY_STATUS, itemClass.getStatus());
db.update(TABLE_NAME, contentValues, KEY_ID + " = ?", new String[]{String.valueOf(itemClass.getId())});
}
public static DataBaseHelper getInstance(){
return dbHelper;
}
}
And when I try to call the UpdateDataBase() method in my other class using
DataBaseHelper.getInstance().UpDateDataBase(new ItemClass());
It tells me that I'm referencing a null object. How do I reference the same instance of the class?
Thank you.
Attempt to invoke virtual method 'void demoapp.app.android.sqlitedatabaseapplication.DataBaseHelper.UpDateDataBase(demoapp.app.android.sqlitedatabaseapplication.ItemClass)' on a null object reference
You need a make your DatabaseHelper class a singleton. A singleton is a design pattern that restricts the instantiation of a class to a single object. Alex Lockwood wrote a really simple and well explained article about this regarding Databases: http://www.androiddesignpatterns.com/2012/05/correctly-managing-your-sqlite-database.html
Also, in Java it is a convention to for your class method names to start with a lowercase letter: updateDatabase instead of UpdateDatabase Camelcase consists in putting a upercase letter at the beginning of a new word in a string without spaces: updateDatabase instead of UpDateDataBase
From Activity
DatabaseHelper databaseHelper=new DatabaseHelper(Your Activity Context)
databaseHelper.methodName();
in DatabaseHelper create a Constructor
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
i hope this will help you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.