【问题标题】:how to send any data from activity to another activity?如何将任何数据从活动发送到另一个活动?
【发布时间】:2014-06-27 20:18:14
【问题描述】:

我有很多活动,在 MainActivity 中有两个按钮 (B1-B2)。在 B1 (Activity1) 中,用户将写入相同的数据并在完成后返回 MainActivity 并且在 B2 (Activity2) 中将从 (Activity1) 获取所有日期

(活动1)

 Intent i = new Intent(getApplicationContext(), Activity2.class);
    i.putExtra("new_variable_name","value");

(活动2)

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


}  

这段代码对我不起作用!!....任何解决方法!!

【问题讨论】:

标签: android-intent bundle


【解决方案1】:

来自 SO 帖子:

Intent i =new Intent(Info.this, GraphDiag.class).putExtra("new_variable_name", "value");
startActivity(i);

获取数据

String value  = getIntent().getStringExtra(<StringName>);

Also look here

【讨论】:

    【解决方案2】:

    您的代码是正确的,我猜是上下文 getApplicationContext() 导致了问题。在活动范围内,最好使用 MyActivity.this 作为上下文参数。试试这个:

    Intent i =new Intent(Activity1.this, Acivity2.class);
    i.putExtra("new_variable_name", "value");
    startActivity(i);
    

    获取额外值并执行空值检查:

    Bundle b = getIntent().getExtras();
    if(b!=null){
    String value = b.getString("new_variable_name");//ensured that the string is not null
    }
    

    【讨论】:

    • 但如何知道它是否为空?
    • 可以使用这个 lain startActivity(i);我不需要 startActivity ...如果用户在转到 Acivity2 之后返回 MainActivity 并将获取 ListView 或 Toast 中的所有数据??
    • 捆绑 b = getIntent().getExtras();当把它放在这个..不适合我
    • 现在可以了,但我不需要 startActivity(i);我想返回并按 B2,然后将获取 ListView 或 Toast 中的所有数据
    • 感谢您的评论..我会尽力解决我的问题,谢谢再试一次
    猜你喜欢
    • 2020-02-11
    • 2019-07-31
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    相关资源
    最近更新 更多