2011-06-27 44 views
1

我有一个需要从第二个活动更新的TextView活动。 我可以将文本视图数据传递给第二个活动,但是当我尝试在第二个活动内更新该TextView 时,它会崩溃。我的代码:无法从其他活动更新TextView

1日活动(其中TextView的是我的XML定义):

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

// code snippet 

然后在我的第二个活动:

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

但是当我尝试拉进来,因为它崩溃a TextView

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

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

请大家帮忙。

+1

请粘贴LogCat异常 – Sarmad

回答

1

您试图将String转换为TextView。该崩溃的代码是等价的:

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

你应该这样做,而不是:

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

第三行导致崩溃:textView.setText(text); – huskyd97

+0

您需要更改'R.id.yourTextViewId'来更正活动布局中文本视图的ID。 – inazaruk

+1

我已更改R.id.yourTextViewId以匹配我在第一个活动布局中所拥有的内容。但我在我的第二个活动中使用它,它如何识别它,因为第二个活动的布局完全不同? thx – huskyd97

3

您试图获取一个字符串作为TextView(您正在设置一个字符串的意图从第一个活动)。

0

这条线的位置:

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

沿着连接字符串的意图,而不是一个TextView 。

您必须在第二个活动中为新的TextView充气,方法是在layout.xml中声明它,或者通过编程将其放置在布局中。

+0

String text =(String)bundle.get(“homescore_value”); TextView textView =(TextView)findViewById(R.id.score_home); // textView.setText(text); - >当我使用这一行时崩溃 – huskyd97

+0

如何膨胀在第二个活动的第一个活动中定义的TextView?我认为这是使用putExtra的原因。以便第二个活动可以识别TextView是什么?我想我在这里失去了一些东西。 thx为你的帮助。 – huskyd97

+0

把'TextView'想象成文本的占位符,而不是实际的文本。 随着意图你会注意到你不能实际发送textView,因为它不是一个基本的数据类型或实现'Parcelable'。 所以基本上当你调用'textView.getText()'你得到它中的字符串,并发送它的意图。因此,'TextView'只是一个用于放置字符串的存储桶/占位符。 您需要设置另一个“TextView”,以便第二个布局知道放置它的位置。 希望可以帮助你:) – manno23

0

东西解决了这个问题,我的部分是接收字符串变量设置为null这样的:

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

我对这个问题我想在几个TextViews,只有设置背景颜色第一个是在这个时候设置。