huskyd97
huskyd97

Reputation: 447

Can't update TextView from another activity

I have an activity with a TextView that needs to be updated from a second activity. I can pass the Text view data to the 2nd activity ok, but when I try to update that TextView within the 2nd activity it crashes. My code:

1st Activity (where the TextView is defined in my xml):

Intent intent = new Intent(1stactivity.this, 2ndactivity.class); 
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
startActivity(intent);

// code snippet

Then in my 2nd activity:

Bundle bundle = getIntent().getExtras();
hometext = bundle.getString("homescore_value"); // this works and displays the correct String from 1st activity, 

but it crashes when I try to pull in as a TextView:

// other code snipped
int homescore = 0;
String Home_nickname = "HOME ";

TextView homestext = (TextView) bundle.get("homescore_value");
hometext.setText(Home_nickname +": "+homescore   );

Please help.

Upvotes: 1

Views: 1421

Answers (4)

marketrow
marketrow

Reputation: 1

Something that solved part of this problem for me was setting the receiving String variables to null like this:

public String param1new = null;
public String param2new= null; 

My issue with this is I'm trying to set background colors on several TextViews and only the first one is being set at this time.

Upvotes: 0

manno23
manno23

Reputation: 184

This line here:

intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());

is attaching a String along with the intent, not a TextView.

You must inflate a new TextView within the 2nd activity, by either declaring it in the layout.xml, or programmatically placing it within the layout.

Upvotes: 0

inazaruk
inazaruk

Reputation: 74780

You trying to cast String to TextView. The code that crashes is equivalent of:

String text = bundle.get("homescore_value"); //this is ok
TextView textView = (TextView)text; //this is bad

You should do instead:

String text = bundle.get("homescore_value");
TextView textView = (TextView)findViewById(R.id.yourTextViewId);
textView.setText(text);

Upvotes: 1

sparkymat
sparkymat

Reputation: 10028

You are trying to get a String as a TextView (you are setting a String in the intent from the first Activity).

Upvotes: 3

Related Questions