繁体   English   中英

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

[英]Intent.putExtra - How to send a string to the next activity?

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

intent.putExtra(EXTRA_MESSAGE, string_to_be_sent)

但这会引发错误,表示EXTRA_MESSAGE不是值-即。 它是由意图识别的。 我认为这个例子已经过时了。 我应该用什么来发送字符串? 我查看了文档,发现了这一点:

public Intent putExtra (String name, String value)

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

第一次活动

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");
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");
}
intent.putExtra("anyNameYouWant", "desired string value");
String product = "hellow"; 
    Intent myintent = new Intent(getApplicationContext(),view1.class);
    myintent.putExtra("product", product);

在发送活动中:

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

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

然后在接收Activity的onCreate方法中:

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

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即可,而不必遍历所有类/活动并搜索使用此String值的位置。

您可以这样做:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM