android-studionullpointerexceptionexplicit-intent

Throws in a NullPointerException when using a getStringExtra in MainActivity


I am currently learning explicit intents and I have followed the coding which was instructed and it always returns a NullPointerException.

This is the code where I enter the data to return to the MainActivity:

if (etSurname.getText().toString().isEmpty())
            {
                Toast.makeText(Activity3.this, "Fill In A Surname!", Toast.LENGTH_SHORT).show();
            }
            else
            {
                String surname=etSurname.getText().toString().trim();
                Intent intent=new Intent();
                intent.putExtra("surname",surname);
                setResult(RESULT_OK,intent);
                Activity3.this.finish();
            }
        }
    });
    btnCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            setResult(RESULT_CANCELED);
            Activity3.this.finish();
        }
    });

and this is the code which i put in the MainActivity which is basically the launcher page where the data i filled in Activity3 is supposed to appear in the textview:

btnAct3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent= new Intent(MainActivity.this, com.example.explicitintents.Activity3.class);
            startActivityForResult(intent, ACTIVITY3);

        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==ACTIVITY3)
    {
        if(resultCode==RESULT_OK)
        {
            tvResults.setText(data.getStringExtra("surname"));
        }

        if(resultCode==RESULT_CANCELED)
        {
            tvResults.setText("no data received!");
        }
    }
}

i have tried using the debug feature and it points to this line:

tvResults.setText(data.getStringExtra("surname")); 

I expect the surname that i filled in the EditText on Activity3 to appear in the MainActivity when I hit the Submit button.

Instead it closes the app and this is what appears in the logcat:

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.explicitintents.MainActivity.onActivityResult(MainActivity.java:69)

Solution

  • Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

    Above error means you are trying to use .setText() method on a null reference TextView.

    So, your problem is you forgot to bind your tvResults with design xml. In your onCreate() method, just add below code.

    TextView tvResults = findViewById(R.id.your_textview_name);  //bind with your tv name in xml