简体   繁体   中英

Exception: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference

When i am trying to add two string variable msg and phoneNo in the TextView through setter method present in MainActivity.java (which is called by dow() method which is present in MyReceiver.java) a Runtime Exception (shown below) occurs When onReceive method in MyReceiver.java file is called by broadcastReceiver . I am unable to understand the Exceptio

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);
    }

}

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>

Exception shown by 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) 

You are trying to instantiate MainActivity on your own. Instead, do the following : 1)Create MyReceiver as an inner class inside MainActivity and register it as usual. 2)Receive the broadcast and update the UI from within onReceive().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM