java – App Forces Close . SMS Broadcast Receiver-ThrowExceptions

Exception or error:

I’m new to Android Studio. when i run this on a single activity it runs okay but when i have a multiple activities it forces to close.

The error

 02-12 00:18:42.578 5092-5092/com.example.driveassist E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.example.driveassist, PID: 5092
        java.lang.RuntimeException: Error receiving broadcast Intent { act=android.provider.Telephony.SMS_RECEIVED flg=0x8000010 (has extras) } in com.example.driveassist.firstPage$1@30b6fb57
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:876)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at com.example.driveassist.firstPage$1.onReceive(firstPage.java:77)
            at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:866)
            at android.os.Handler.handleCallback(Handler.java:739) 
            at android.os.Handler.dispatchMessage(Handler.java:95) 
            at android.os.Looper.loop(Looper.java:135) 
            at android.app.ActivityThread.main(ActivityThread.java:5254) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at java.lang.reflect.Method.invoke(Method.java:372) 
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

my activity codes are

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.speech.tts.TextToSpeech;
import android.telephony.SmsMessage;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class firstPage extends AppCompatActivity {
    private Button button,btbutton,acbutton;
    private final int CHECK_CODE = 0x1;
    private final int LONG_DURATION = 2000;
    private final int SHORT_DURATION = 1200;

    private Speaker speaker;

    private ToggleButton toggle;
    private CompoundButton.OnCheckedChangeListener toggleListener;

    private TextView smsText;
    private TextView smsSender;

    private BroadcastReceiver smsReceiver;
    private String address;

    private void checkTTS(){
        Intent check = new Intent();
        check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(check, CHECK_CODE);
    }
    @SuppressLint("MissingSuperCall")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CHECK_CODE){
            if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
                speaker = new Speaker(this);
            }else {
                Intent install = new Intent();
                install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(install);
            }
        }
    }
    private void initializeSMSReceiver(){
        smsReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {

                Bundle bundle = intent.getExtras();
                if(bundle!=null){
                    Object[] pdus = (Object[])bundle.get("pdus");
                    for(int i=0;i<pdus.length;i++){
                        byte[] pdu = (byte[])pdus[i];
                        SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[0]);
                        String text = message.getDisplayMessageBody();
                        address = message.getOriginatingAddress();
                        String sender = getContactName(message.getOriginatingAddress());
                        speaker.pause(LONG_DURATION);
                        speaker.speak("You have a new message from" + sender + "!");
                        speaker.pause(SHORT_DURATION);
                        speaker.speak(text);
                        smsSender.setText("Message from " + sender);
                        smsText.setText(text);

                    }
                }

            }
        };
    }
    private String getContactName(String phone){
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
        String projection[] = new String[]{ContactsContract.Data.DISPLAY_NAME};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if(cursor.moveToFirst()){
            return cursor.getString(0);
        }else {
            return address;
        }
    }

    private void registerSMSReceiver() {
        IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(smsReceiver, intentFilter);
    }


    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_first_page);

        toggle = (ToggleButton)findViewById(R.id.speechToggle);
        //smsText = (TextView)findViewById(R.id.sms_text);
        smsSender = (TextView)findViewById(R.id.senderView);

        toggleListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton view, boolean isChecked) {
                if(isChecked){
                    speaker.allow(true);
                    speaker.speak(getString(R.string.start_speaking));
                }else{
                    speaker.speak(getString(R.string.stop_speaking));
                    speaker.allow(false);
                }
            }
        };
        toggle.setOnCheckedChangeListener(toggleListener);

        checkTTS();
        initializeSMSReceiver();
        registerSMSReceiver();


    button =(Button) findViewById(R.id.settingsButton);
            button.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View V) {
                    openActivity3();

                }
            });
            btbutton =(Button) findViewById(R.id.btsettingsButton);
            btbutton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View V) {
                    btActivity();

                }
            });
            acbutton = (Button) findViewById(R.id.acceptButton);
            acbutton.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View V) {
                    readActivity();

                }
            });
        }
        public void openActivity3() {
            Intent intent = new Intent(this,editMessage.class);
            startActivity(intent);
        }
        public void btActivity() {
            Intent intent1 = new Intent(this,btConnectivity.class);
            startActivity(intent1);
        }
        public void readActivity() {
            Intent intent2 = new Intent(this,readMessage.class);
            startActivity(intent2);
        }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(smsReceiver);
        speaker.destroy();
    }

    }
How to solve:

Following error message means that dereference to the TextView type reference which was null occurred to try call setText method. It caused error message when you receive Broadcast intent.

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.driveassist.firstPage$1.onReceive(firstPage.java:77)

And there’s one concerned point in your onReceive implementation.
onReceive
-> smsText.setText(text); <- smsText hasn’t allocated. because of the line comment

onCreate
-> //smsText = (TextView)findViewById(R.id.sms_text);

Leave a Reply

Your email address will not be published. Required fields are marked *