使用Intents发送时,字符串为空

时间:2016-08-28 16:40:21

标签: android android-intent

我正在尝试使用意图将一个String从一个活动发送到另一个活动,但是当我发送它并将TextView设置为该字符串时,该字符串为空。这是意图代码:

String homeTeam = "temp";
String awayTeam = "temp";

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gaelic_param);

    EditText homeTeamEditText = (EditText) findViewById(R.id.HomeTeam);
    EditText awayTeamEditText = (EditText) findViewById(R.id.AwayTeam);

    homeTeam = homeTeamEditText.getText().toString();
    awayTeam = awayTeamEditText.getText().toString();
}

public void nextPage(View view)
{
    Intent intent = new Intent(GaelicParam.this, GaelicActivity.class);
    intent.putExtra("homeTeamExtra", homeTeam);
    startActivity(intent);
}

以下是我设置文字的方法。

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gaelic_main);

    Bundle extras = getIntent().getExtras();
    if(extras != null) {
        String HomeTeam = extras.getString("homeTeamExtra");

        TextView homeTextView = (TextView)findViewById(R.id.homeTeam_text_view);
        homeTextView.setText(HomeTeam);
    }
}

但是textView仍然是空的。

3 个答案:

答案 0 :(得分:0)

使用方法 getStringExtra 从putExtra(字符串值)中检索

intent.getStringExtra("homeTeamExtra");

答案 1 :(得分:0)

使用此代码 将homeTeam = homeTeamEditText.getText().toString();置于内部,以便获取editText的最新值

public void nextPage(View view){
homeTeam = homeTeamEditText.getText().toString();
Intent intent = new Intent(GaelicParam.this, GaelicActivity.class);
intent.putExtra("homeTeamExtra", homeTeam);
startActivity(intent);
}

答案 2 :(得分:0)

看起来homeTeam仅在创建时在发送活动中设置,因此它不会反映对EditText的任何更改。解决此问题的最简单方法是在请求下一页时检索EditText中的文本,例如:

public void nextPage(View view) {
    EditText homeTeamEditText = (EditText) findViewById(R.id.HomeTeam);
    Intent intent = new Intent(GaelicParam.this, GaelicActivity.class);
    intent.putExtra("homeTeamExtra", homeTeamEditText.getText().toString());
    startActivity(intent);
}

如果您希望homeTeam始终反映EditText中的当前文字,可以尝试使用TextWatcher