我目前正在尝试开发一个短信应用程序,它运行并且能够检索消息,但是一旦你关闭应用程序并重新启动它,它会强制关闭,它说有一个NullPointerException。 这是错误日志。列表可能是原因,但我不知道为什么,StackOverflow不允许我发布这个没有添加其他信息,我真的不知道要添加什么。
08-08 16:08:17.317 9977-9977/backdev.messages E/AndroidRuntime: FATAL EXCEPTION: main
Process: backdev.messages, PID: 9977
java.lang.RuntimeException: Unable to start activity ComponentInfo{backdev.messages/backdev.messages.MessageActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at backdev.messages.MessageActivity.refreshSMSInbox(MessageActivity.java:136)
at backdev.messages.MessageActivity.getPermissionToReadSMS(MessageActivity.java:118)
at backdev.messages.MessageActivity.onCreate(MessageActivity.java:78)
at android.app.Activity.performCreate(Activity.java:6323)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
这是我的代码:
private static final int READ_SMS_PERMISSIONS_REQUEST =1;
private Context mContext = MessageActivity.this;
private static final String TAG = "MessageActivity";
private List<PreviewMessage> mPreviewMessages;
private RecyclerView rvMessages;
private static MessageActivity inst;
private RecyclerView.Adapter mMessagesAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
rvMessages = (RecyclerView) findViewById(R.id.rvMessages);
rvMessages.setHasFixedSize(true);
rvMessages.setLayoutManager(new LinearLayoutManager(mContext));
getPermissionToReadSMS();
mPreviewMessages = new ArrayList<>();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
!= PackageManager.PERMISSION_GRANTED) {
getPermissionToReadSMS();
} else {
refreshSMSInbox();
}
}
public void getPermissionToReadSMS(){
Log.d(TAG, "getPermissionToReadSMS: getting permission");
if(ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_SMS)!= PackageManager.PERMISSION_GRANTED){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(Manifest.permission.READ_SMS)){
Log.d(TAG, "getPermissionToReadSMS: requesting Permission again");
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
Toast.makeText(mContext,"Application will not work without this permission", Toast.LENGTH_SHORT).show();
requestPermissions(new String[]{Manifest.permission.READ_SMS},READ_SMS_PERMISSIONS_REQUEST);
}
// No explanation needed, we can request the permission.
//display explanation first --- not yet done
Log.d(TAG, "getPermissionToReadSMS: requestPermission");
requestPermissions(new String[]{Manifest.permission.READ_SMS},READ_SMS_PERMISSIONS_REQUEST);
}
}else{
refreshSMSInbox();
}
}
private void refreshSMSInbox() {
ContentResolver contentResolver = getContentResolver();
Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"),null,null,null,null);
int indexBody = smsInboxCursor.getColumnIndex("body");
int indexAddress = smsInboxCursor.getColumnIndex("address");
while (smsInboxCursor.moveToNext()) {
PreviewMessage previewMessage = new PreviewMessage(smsInboxCursor.getString(indexAddress),smsInboxCursor.getString(indexBody), 1);
/*
ERROR HERE
*/
mPreviewMessages.add(previewMessage);
}
mMessagesAdapter = new MessagesAdapter(mPreviewMessages,mContext);
rvMessages.setAdapter(mMessagesAdapter);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 1:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//granted do things here
//read sms
refreshSMSInbox();
}else {
}
}
}
答案 0 :(得分:3)
仔细查看堆栈,你会看到onCreate正在调用getPermissionToReadSms,而getPermissionToReadSms又调用了refreshSmsBox,它试图将一个元素添加到列表mPreviewMessages中。
在调用getPermissionToReadSms后,在onCreate中初始化此列表。这就是为什么它会抛出空的例外。
只需将mPreviewMessages初始化移到getPermissionToReadSms调用之上,它就会起作用。
答案 1 :(得分:0)
在向其添加数据之前初始化列表。因为getPermissionToReadSMS();
调用了refreshSMSInbox();`如果操作系统低于Marshmallow,它会尝试在初始化之前将数据添加到列表中
mPreviewMessages = new ArrayList<>();
getPermissionToReadSMS();