I am trying to access cursor in a class which needs a context to call and need a activity to start startManagingCursor function.
In a activity i called my class like this.
backupSMS b=new backupSMS(getBaseContext(),backupOptions.this);
b.BackUpAllSms();
and i wrote backupSMS class like this:
public class backupSMS {
Context context;
Activity myActivity;
public backupSMS(Context con, Activity application) {
context = con;
myActivity = application;
Log.d("context", "con: " + context + " act: " + myActivity);
BackUpAllSms();
}
@SuppressWarnings("deprecation")
public void BackUpAllSms() {
ArrayList<SmsDataClass> all_sms_data = new ArrayList<SmsDataClass>();
// backup all sms
Uri uri = Uri.parse("content://sms");
Cursor c = context.getContentResolver().query(uri, null, null, null,
null);
myActivity.startManagingCursor(c);
// Read the sms data and store it in the list
if (c.moveToFirst()) {
for (int i = 0; i < c.getCount(); i++) {
SmsDataClass sms = new SmsDataClass();
sms.setAddress(c.getString(c.getColumnIndexOrThrow("address"))
.toString());
sms.setBody(c.getString(c.getColumnIndexOrThrow("body"))
.toString());
all_sms_data.add(sms);
c.moveToNext();
}
}
c.close();
}
}
But it shows a nullpointer exception. But if i write the BackUpAllSms() function into my backupOptions activity then it works fine. What is the problem here ??
My logCat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.smsbackup.backupSMS.BackUpAllSms(backupSMS.java:74)
at com.example.smsbackup.backupSMS.<init>(backupSMS.java:51)
at com.example.smsbackup.backupOptions$3.onClick(backupOptions.java:67)
at android.view.View.performClick(View.java:4212)
at android.view.View$PerformClick.run(View.java:17476)
06-13 11:42:19.205: E/AndroidRuntime(12771): at android.os.Handler.handleCallback(Handler.java:800)
06-13 11:42:19.205: E/AndroidRuntime(12771): at android.os.Handler.dispatchMessage(Handler.java:100)
06-13 11:42:19.205: E/AndroidRuntime(12771): at android.os.Looper.loop(Looper.java:194)
06-13 11:42:19.205: E/AndroidRuntime(12771): at android.app.ActivityThread.main(ActivityThread.java:5371)
06-13 11:42:19.205: E/AndroidRuntime(12771): at java.lang.reflect.Method.invokeNative(Native Method)
06-13 11:42:19.205: E/AndroidRuntime(12771): at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
First thing first, this part of your code:
..and therefore your backupSms class' constructor, is redundant.
Activity
extendsContext
, so they're pretty much the same thing. You should just make the constructor like this:And use
mActivity
for every operation that might need throughout the class.Also, call this when creating backupSms: