我的问题是,当我尝试在下面的代码中设置service1和service1Health的文本时,文本未被设置。关于为什么会发生这种情况的任何想法? service1Name和service1HealthValue都具有有效的字符串值。
public void onClick(View v)
{
switch(v.getId())
{
case R.id.loginButton:
String[] values = new String[2];
String usernameText = ((TextView) activity.findViewById(R.id.usernameTextBox)).getText().toString();
String passwordText = ((TextView) activity.findViewById(R.id.txtPasswordField)).getText().toString();
if (usernameText.length()==0 || passwordText.length()==0)
Toast.makeText(activity, "Please fill in both username and password fields", Toast.LENGTH_SHORT).show();
else
{
Toast.makeText(activity, "Connecting to server", Toast.LENGTH_LONG).show();
String loginResult = Server.login(usernameText,passwordText);
values = loginResult.split(",");
Intent i = new Intent(activity,Home.class);
activity.startActivity(i);
activity.setContentView(R.layout.home);
String service1Name = Server.getServices("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
String service1HealthValue = Server.getHealth("myservice","xxxxxxxxxxxxxxxxxxxxxxxxxxx");
TextView service1= ((TextView) activity.findViewById(R.id.serviceName1));
TextView service1Health= ((TextView) activity.findViewById(R.id.service1Health));
service1.setText(service1Name);
service1Health.setText(service1HealthValue);
}
break;
}
}
答案 0 :(得分:2)
当您致电activity.startActivity(i);
时,它会启动一项新活动,因此无法访问此后的任何代码,包括activity.setContentView(R.layout.home);
,因此这些TextViews
都不会设置。如果要在新活动中设置这些值,则应将其添加到Intent
,然后在新onCreate
的{{1}}方法中重新打开它们。例如,在您当前的活动中:
Activity
在Intent i = new Intent(activity,Home.class);
i.putExtra("service1Name", Server.getServices("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
i.putExtra("service1HealthValue", Server.getHealth("myservice","xxxxxxxxxxxxxxxxxxxxxxxxxxx"));
activity.startActivity(i);
的onCreate方法中,添加以下内容:
Home.java