java异常:尝试调用虚拟方法“安卓”。所容纳之物资源安卓。所容纳之物上下文空对象引用上的getResources()
当我试图通过MainActivity中的setter方法在文本视图中添加两个字符串变量msg和phoneNo时。java(由MyReceiver中的dow()方法调用)。java)运行时异常(如下所示) 当MyReceiver中的onReceive方法时发生。java文件由广播接收器调用。我无法理解这个例外
主要活动。爪哇
package com.example.smsreceiver;
import 安卓x.annotation.NonNull;
import 安卓x.appcompat.app.AppCompatActivity;
import 安卓x.core.app.ActivityCompat;
import 安卓x.core.content.ContextCompat;
import 安卓.Manifest;
import 安卓.content.pm.PackageManager;
import 安卓.os.Bundle;
import 安卓.widget.TextView;
import 安卓.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSION_REQUEST_RECEIVE_SMS = 0;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView2);
//check if the permission is not granted
if(ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {
if(!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECEIVE_SMS)) {
//a pop up will appear asking for required permission i.e. Allow or Deny
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, MY_PERMISSION_REQUEST_RECEIVE_SMS);
}
}
//this.setter();
}//onCreate
//after getting the result of permission request the result will be passed through this method
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
//will check the requestCode
if (requestCode == MY_PERMISSION_REQUEST_RECEIVE_SMS) {//check whether the length of grantResults is greater than 0 and is equal to PERMISSION_GRANTED
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Now broadcast receiver work in background
Toast.makeText(this, "Thank you for permitting!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Well I can't do anything until you permit me", Toast.LENGTH_LONG).show();
}
}
}
public void setter(String msg, String phoneNo){
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView2);
String hi = msg + phoneNo;
textView.setText(hi);
Toast.makeText(this, "message: " + msg + "\n Number: " + phoneNo, Toast.LENGTH_LONG).show();
}
}
我的接收器。爪哇
package com.example.smsreceiver;
import 安卓.content.BroadcastReceiver;
import 安卓.content.Context;
import 安卓.content.Intent;
import 安卓.os.Bundle;
import 安卓.telephony.SmsMessage;
import 安卓.util.Log;
import 安卓.widget.Toast;
import java.util.Objects;
public class MyReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "安卓.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SmsBroadcastReceiver";
public static String msg, phoneNo = "";
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent Received: " + intent.getAction());
if(Objects.equals(intent.getAction(), SMS_RECEIVED)) {
//retrieves a map of extended data from the intent
Bundle dataBundle = intent.getExtras();
if (dataBundle != null) {
//create an PDU(Protocol Data Unit) object which is a protocol for transferring message
Object[] mypdu = (Object[])dataBundle.get("pdus");
final SmsMessage[] message = new SmsMessage[mypdu.length];
for (int i = 0; i < mypdu.length; i++) {
//for build version >= API Level 23 (Build.VERSION_CODES.M)
String format = dataBundle.getString("format");
//from PDU we get all abject and SmsMessage Object using following line of code
message[i] = SmsMessage.createFromPdu((byte[]) mypdu[i], format);
msg = message[i].getMessageBody();
phoneNo = message[i].getOriginatingAddress();
}
Toast.makeText( context, "message: " + msg + "\n NUmber: " + phoneNo, Toast.LENGTH_LONG).show();
dow(msg, phoneNo);
}
}
}
public void dow(String msg, String phoneNo){
MainActivity mainActivity = new MainActivity();
mainActivity.setter(msg, phoneNo);
}
}
主要活动。xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:app="http://schemas.安卓.com/apk/res-auto"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
安卓:orientation="vertical"
tools:context=".MainActivity">
<TextView
安卓:id="@+id/textView2"
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
安卓:gravity="center"
安卓:textSize="24sp"
/>
</LinearLayout>
Logcat显示的异常
Process: com.example.smsreceiver, PID: 18414
java.lang.RuntimeException: Unable to start receiver com.example.smsreceiver.MyReceiver: java.lang.NullPointerException: Attempt to invoke virtual method '安卓.content.res.Resources 安卓.content.Context.getResources()' on a null object reference
at 安卓.app.ActivityThread.handleReceiver(ActivityThread.java:3665)
at 安卓.app.ActivityThread.access$1500(ActivityThread.java:219)
at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1850)
at 安卓.os.Handler.dispatchMessage(Handler.java:106)
at 安卓.os.Looper.loop(Looper.java:227)
at 安卓.app.ActivityThread.main(ActivityThread.java:7200)
at java.lang.reflect.Method.invoke(Native Method)
at com.安卓.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:575)
at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:903)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method '安卓.content.res.Resources 安卓.content.Context.getResources()' on a null object reference
at 安卓.content.ContextWrapper.getResources(ContextWrapper.java:91)
at 安卓.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
at 安卓.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
at 安卓x.appcompat.app.AppCompatActivity.getResources(AppCompatActivity.java:543)
at 安卓.widget.Toast.<init>(Toast.java:139)
at 安卓.widget.Toast.makeText(Toast.java:306)
at 安卓.widget.Toast.makeText(Toast.java:296)
at com.example.smsreceiver.MainActivity.setter(MainActivity.java:60)
at com.example.smsreceiver.MyReceiver.dow(MyReceiver.java:51)
at com.example.smsreceiver.MyReceiver.onReceive(MyReceiver.java:45)
at 安卓.app.ActivityThread.handleReceiver(ActivityThread.java:3649)
at 安卓.app.ActivityThread.access$1500(ActivityThread.java:219)
at 安卓.app.ActivityThread$H.handleMessage(ActivityThread.java:1850)
at 安卓.os.Handler.dispatchMessage(Handler.java:106)
at 安卓.os.Looper.loop(Looper.java:227)
at 安卓.app.ActivityThread.main(ActivityThread.java:7200)
at java.lang.reflect.Method.invoke(Native Method)
at com.安卓.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:575)
at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:903)
# 1 楼答案
您正在尝试自己实例化MainActivity。相反,请执行以下操作: 1) 在MainActivity中创建MyReceiver作为内部类,并像往常一样注册它。 2) 接收广播并从onReceive()中更新UI