EightSquared
EightSquared

Reputation: 37

Android .putExtra (not responding)

I need to pass a String created from 'Activity A' to 'Activity B' so that I can display it in a TextView. The problem is that the code causes Android to not respond, its identical to the other tutorials online.

Thanks for any feedback.

Activity A.onCreate()

check_button = (Button) findViewById(R.id.check_button);
    check_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            Intent i = new Intent(AddActivity.this, DetailActivity.class);
            String hash = text_hash.toString();
            i.putExtra("hash" , hash);
            startActivity(i);
        }
    });

Activity B.onCreate()

Bundle extras = getIntent().getExtras();
if (extras != null)
{
    passedHash = (String) getIntent().getExtras().getString("hash");
    hash.setText(passedHash);
}

stack trace:

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

Upvotes: 0

Views: 46

Answers (4)

your textView object is nullreferenced, you need to initialize the hash variable in the oncreate before you begin to call any method of that TextView...

Example:

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    TextView hash = (TextView)findViewById(R.id.hash_textview);

after that you can call the settext method

 hash.setText(passedHash);

Upvotes: 0

Md. Sajedul Karim
Md. Sajedul Karim

Reputation: 7075

If text_hash is TextView or EditText then use use

String hash = text_hash.getText().toString();

In ActivityB onCreate() use this:

String newString;
if (savedInstanceState != null) {
    Bundle extras = getIntent().getExtras();
    if(extras == null) {
        newString= null;
    } else {
        newString= extras.getString("hash");
    }
}

EDIT From your error log, You didn't initialize TextView in your ActivityB. First you have to initialize that TextView then set Text.

Upvotes: 0

Omar Aflak
Omar Aflak

Reputation: 2962

According to your log, it seems that you didn't initialize your TextView in Activity B. Do this before setting the text to your TextView:

TextView hash = (TextView)findViewById(R.id.hash_textview);

Upvotes: 1

EightSquared
EightSquared

Reputation: 37

Ok, so I needed to use X.getText().toString(); By reading the stack trace I figured I also needed to findViewByID on the TextView BEFORE trying to set text.

Thanks for reading.

Upvotes: 0

Related Questions