Intent.putExtra - 如何将字符串发送到下一个活动?

时间:2014-01-04 12:08:06

标签: java android eclipse android-intent

好的,我根据用户输入的一些数据创建一个简单的字符串。我现在希望这些数据作为字符串(像字符串一样的CSV)传递到下一个活动。在一个例子中,我看到了这一点:

intent.putExtra(EXTRA_MESSAGE, string_to_be_sent)

但是这会引发错误,说EXTRA_MESSAGE不是值 - 即。它被意图所认可。我认为这个例子已经过时了。我应该用什么来发送字符串?我查看了文档,发现了这个:

public Intent putExtra (String name, String value)

但是我的价值是什么?我选择的任何东西,还是必须是包名? 谢谢你的帮助:)

6 个答案:

答案 0 :(得分:4)

第一项活动

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable Name",string_to_be_sent);
startActivity(intent);

第二项活动

//Receiving data inside onCreate() method of Second Activity
String value = getIntent().getStringExtra("Variable Name");

答案 1 :(得分:2)

Intent intent= new Intent(currentActivity.this, TheActivityYouWant to Start.class);
intent.putExtra("SOME_KEY", "Sending");
startActivity(intent);

要在其他活动中检索此内容,请在已启动的活动onCreate(Bundle savedInstanceState)中执行此操作。

Bundle bundle = getIntent().getExtras();
if(bundle != null) {
String your_extra = bundle.getString("SOME_KEY");
}

答案 2 :(得分:1)

intent.putExtra("anyNameYouWant", "desired string value");

答案 3 :(得分:1)

String product = "hellow"; 
    Intent myintent = new Intent(getApplicationContext(),view1.class);
    myintent.putExtra("product", product);

答案 4 :(得分:1)

在发送活动中:

 String EXTRA_MESSAGE = "Your string to be sent.."

    intent.putExtra(EXTRA_MESSAGE, EXTRA_MESSAGE ); 
    startActivity(intent);

然后在onCreate接收Activity的方法:

    Bundle bundle= getIntent().getExtras();
    String stringtoBeReceived = bundle.getString(EXTRA_MESSAGE);

答案 5 :(得分:0)

EXTRA_MESSAGE当然意味着它是static final String值。

当其他人回答如何使用它时,我想补充一点,创建一个Utils类将帮助您更灵活地维护代码。即,您可以创建一个Utils类来保存所有常量值。

final class Utils {
  private Utils(){}//avoid useless instantiation of the class
  private final static String EXTRA_MESSAGE = "extraMessage";
}

现在,如果你想改变这个String的值,你只需要改变这个,不要遍历你所有的类/活动,并搜索你使用这个String值的地方。

你可以这样做:

myintent.putExtra(Utils.EXTRA_MESSAGE, "theMessage");
String extra = bundle.getString(Utils.EXTRA_MESSAGE);

现在,如果您想更改EXTRA_MESSAGE的值,则只需在Utils类中对其进行修改。