任何人都可以帮助我理解为什么以下代码无法将多个信息值从一个活动传递到另一个活动。一切似乎没有问题,直到它达到第二个活动,然后传递的第二个元素(messageTwo)不被识别。
public class ChooseYourRestaurant extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.macuser.biteresourcebuild.";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_your_restaurant);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = findViewById(R.id.setCalories);
textView.setText(message);
}
/**
* Called when send button clicked
*/
public void sendMessage(View view) {
Intent intent = new Intent(this, MenuSelector.class);
TextView editText = findViewById(R.id.autoCompleteTextView);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
TextView textView1 = findViewById(R.id.calorieTarget);
String messageTwo = textView1.getText().toString();
intent.putExtra(EXTRA_MESSAGE, messageTwo);
startActivity(intent);
}
}
然后我转到另一个活动
public class MenuSelector extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.macuser.biteresourcebuild.";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_selector);
Intent intent = getIntent();
String message = intent.getStringExtra(ChooseYourRestaurant.EXTRA_MESSAGE);
TextView textView = findViewById(R.id.restaurantName);
textView.setText(message);
TextView textView1 = findViewById(R.id.calorieTarget);
textView.setText(messageTwo);
}
}
事情破裂了。而对于我的生活,我不明白为什么。我只编写了一段时间,所以请原谅我,如果它是非常基本的东西。
答案 0 :(得分:0)
您应该为不同的值使用不同的键。例如:EXTRA_MESSAGE1,EXTRA_MESSAGE2
public void sendMessage(View view) {
Intent intent = new Intent(this, MenuSelector.class);
TextView editText = findViewById(R.id.autoCompleteTextView);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE1, message);
TextView textView1 = findViewById(R.id.calorieTarget);
String messageTwo = textView1.getText().toString();
intent.putExtra(EXTRA_MESSAGE2, messageTwo);
startActivity(intent);
}
在第二项活动中,您可以使用
获取它 String message1 = intent.getStringExtra(ChooseYourRestaurant.EXTRA_MESSAGE1);
String message2 = intent.getStringExtra(ChooseYourRestaurant.EXTRA_MESSAGE2);