I have a problem with updating three values in a table.While I am calling that function in a java class which will not have activity.if I use that code in in class where the activity is existing that works.
this is the databasehelper class code
public DatabaseHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, 1);
}
public DatabaseHelper() {
super(null, DATABASE_NAME, null, 1);
}
public boolean updateData(String subject, double present, double total) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, subject);
contentValues.put(COL_2, present);
contentValues.put(COL_3, total);
db.update(TABLE_NAME, contentValues, "SUBJECT = ?", new String[]{subject});
return true;
}
this is the class where i call the fuction
private DatabaseHelper myDb = new DatabaseHelper();
public subject_class(){};
public subject_class(String subject, double num1, double num2) {
this.subject = subject;
this.num1 = num1;
this.num2 = num2;
}
public void update(String sub,double num1,double num2) {
myDb.update1(sub,num1,num2);
}
Error is as follows
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223) at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163) at com.example.sravan.test.DatabaseHelper.update1(DatabaseHelper.java:129) at com.example.sravan.test.subject_class.update(subject_class.java:27) at com.example.sravan.test.subjectlistadapter$1.onClick(subjectlistadapter.java:70) at android.view.View.performClick(View.java:5721) at android.widget.TextView.performClick(TextView.java:10931) at android.view.View$PerformClick.run(View.java:22620) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:7409) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
thanks in advance
make a static global variable
static Context appContext;
and assign the application context in appContext.
appContext=getApplicationContext();
in main activity's onCreate() method. now access it in your non-activity class.
new SetSql(MainActivity.appContext);