Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 异常:尝试调用虚拟方法';android.content.res.Resources android.content.Context.getResources()';关于空对象引用_Java_Android - Fatal编程技术网

Java 异常:尝试调用虚拟方法';android.content.res.Resources android.content.Context.getResources()';关于空对象引用

Java 异常:尝试调用虚拟方法';android.content.res.Resources android.content.Context.getResources()';关于空对象引用,java,android,Java,Android,当我试图通过MainActivity.java中的setter方法(由MyReceiver.java中的dow()方法调用)在TextView中添加两个字符串变量msg和phoneNo时,运行时异常(如下所示) 当broadcastReceiver调用MyReceiver.java文件中的onReceive方法时发生。我无法理解这个例外 MainActivity.java package com.example.smsreceiver; import androidx.annotation.N

当我试图通过MainActivity.java中的setter方法(由MyReceiver.java中的dow()方法调用)在TextView中添加两个字符串变量msgphoneNo时,运行时异常(如下所示) 当broadcastReceiver调用MyReceiver.java文件中的onReceive方法时发生。我无法理解这个例外

MainActivity.java

package com.example.smsreceiver;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import android.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();

    }

}
MyReceiver.java

package com.example.smsreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

import java.util.Objects;

public class MyReceiver extends BroadcastReceiver {

    private static final  String SMS_RECEIVED = "android.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);
    }

}
package com.example.smsreceiver;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.Intent;
导入android.os.Bundle;
导入android.telephony.sms消息;
导入android.util.Log;
导入android.widget.Toast;
导入java.util.Objects;
公共类MyReceiver扩展了BroadcastReceiver{
私有静态最终字符串SMS_RECEIVED=“android.provider.Telephony.SMS_RECEIVED”;
私有静态最终字符串TAG=“SmsBroadcastReceiver”;
公共静态字符串msg,phoneNo=“”;
@凌驾
公共void onReceive(上下文、意图){
Log.i(标记“Intent Received:+Intent.getAction());
if(Objects.equals(intent.getAction(),收到SMS_)){
//从目标中检索扩展数据的映射
Bundle-dataBundle=intent.getExtras();
如果(数据绑定!=null){
//创建PDU(协议数据单元)对象,该对象是用于传输消息的协议
Object[]mypdu=(Object[])dataBundle.get(“PDU”);
最终SmsMessage[]消息=新SmsMessage[mypdu.length];
对于(int i=0;i=API级别23(build.version\u code.M)
字符串格式=dataBundle.getString(“格式”);
//从PDU中,我们使用以下代码行获得所有abject和SmsMessage对象
message[i]=SmsMessage.createFromPdu((字节[])mypdu[i],格式);
msg=message[i].getMessageBody();
phoneNo=消息[i]。getOriginatingAddress();
}
Toast.makeText(上下文,“message:+msg+”\n NUmber:+phoneNo,Toast.LENGTH_LONG).show();
道指(味精、电话号码);
}
}
}
公共无效dow(字符串消息,字符串电话号码){
MainActivity MainActivity=新的MainActivity();
mainActivity.setter(消息、电话号码);
}
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android: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 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:3665)
        at android.app.ActivityThread.access$1500(ActivityThread.java:219)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1850)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:227)
        at android.app.ActivityThread.main(ActivityThread.java:7200)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:575)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:903)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
        at android.content.ContextWrapper.getResources(ContextWrapper.java:91)
        at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
        at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
        at androidx.appcompat.app.AppCompatActivity.getResources(AppCompatActivity.java:543)
        at android.widget.Toast.<init>(Toast.java:139)
        at android.widget.Toast.makeText(Toast.java:306)
        at android.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 android.app.ActivityThread.handleReceiver(ActivityThread.java:3649)
        at android.app.ActivityThread.access$1500(ActivityThread.java:219) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1850) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:227) 
        at android.app.ActivityThread.main(ActivityThread.java:7200) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:575) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:903) 
Process:com.example.smsreceiver,PID:18414
java.lang.RuntimeException:无法启动receiver com.example.smsreceiver.MyReceiver:java.lang.NullPointerException:尝试对空对象引用调用虚拟方法“android.content.res.Resources android.content.Context.getResources()”
位于android.app.ActivityThread.HandlerReceiver(ActivityThread.java:3665)
在android.app.ActivityThread.access,售价1500美元(ActivityThread.java:219)
在android.app.ActivityThread$H.handleMessage(ActivityThread.java:1850)
位于android.os.Handler.dispatchMessage(Handler.java:106)
位于android.os.Looper.loop(Looper.java:227)
位于android.app.ActivityThread.main(ActivityThread.java:7200)
位于java.lang.reflect.Method.invoke(本机方法)
位于com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:575)
位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:903)
原因:java.lang.NullPointerException:尝试对空对象引用调用虚拟方法“android.content.res.Resources android.content.Context.getResources()”
位于android.content.ContextWrapper.getResources(ContextWrapper.java:91)
在android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
在android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
位于androidx.appcompat.app.AppCompatActivity.getResources(AppCompatActivity.java:543)
在android.widget.Toast.(Toast.java:139)
位于android.widget.Toast.makeText(Toast.java:306)
位于android.widget.Toast.makeText(Toast.java:296)
位于com.example.smsreceiver.MainActivity.setter(MainActivity.java:60)
位于com.example.smsreceiver.MyReceiver.dow(MyReceiver.java:51)
位于com.example.smsreceiver.MyReceiver.onReceive(MyReceiver.java:45)
位于android.app.ActivityThread.HandlerReceiver(ActivityThread.java:3649)
在android.app.ActivityThread.access,售价1500美元(ActivityThread.java:219)
在android.app.ActivityThread$H.handleMessage(ActivityThread.java:1850)
位于android.os.Handler.dispatchMessage(Handler.java:106)
位于android.os.Looper.loop(Looper.java:227)
位于android.app.ActivityThread.main(ActivityThread.java:7200)
位于java.lang.reflect.Method.invoke(本机方法)
位于com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:575)
位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:903)

您正在尝试自己实例化MainActivity。相反,请执行以下操作: 1) 在MainActivity中创建MyReceiver作为内部类,并像往常一样注册它。
2) 接收广播并从onReceive()内更新UI

确保
com.example.smsreceiver.MyReceiver
NOT NULL
,并通过在日志中打印其
hashcode
正确实例化。您无法执行此操作:
MainActivity MainActivity=new MainActivity()。这就是问题所在。创建活动的实例。始终使用由系统创建的。然后,我必须编写的内容将按照我在您的ma中定义的MyReceiver activity(MyReceiver活动)进行管理