我正在尝试在需要调用上下文的类中访问游标,并且需要一个活动来启动startManagingCursor函数。
在一项活动中,我这样称呼我的班级。
backupSMS b=new backupSMS(getBaseContext(),backupOptions.this);
b.BackUpAllSms();
我写了这样的backupSMS类:
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();
}
}
但它显示了一个nullpointer异常。 但是,如果我将BackUpAllSms()函数写入我的backupOptions活动,那么它可以正常工作。这有什么问题?
我的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)
答案 0 :(得分:0)
首先,这部分代码:
backupSMS b=new backupSMS(getBaseContext(), backupOptions.this);
..因此你的backupSms类的构造函数是多余的。 Activity
延伸Context
,所以它们几乎是一样的。你应该像这样构建构造函数:
private Activity mActivity;
public backupSms(Activity a) {
mActivity = a;
}
并对整个班级可能需要的每项操作使用mActivity
。
另外,在创建backupSms时调用它:
backupSMS b=new backupSMS(this);