>我目前正在尝试开发一个 SMS 应用程序,它正在运行并且能够检索消息,但是一旦您关闭应用程序并重新启动它,它就会强制关闭,它说有一个 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 {
}
}
}
仔细查看堆栈,您会发现onCreate正在调用getPermissionToReadSms,而getPermissionToReadSms又调用了refreshSmsBox,它试图将元素添加到列表中mPreviewMessages。
在调用 getPermissionToReadSms 后,在 onCreate 中初始化此列表。所以这就是为什么它抛出空例外。
只需将您的mPreviewMessages初始化移动到getPermissionToReadSms调用上方,它就会起作用。
在向列表添加数据之前初始化列表。因为getPermissionToReadSMS();
调用 refreshSMSInbox((;' 如果操作系统低于棉花糖,它会尝试在初始化之前将数据添加到列表中
mPreviewMessages = new ArrayList<>();
getPermissionToReadSMS();