如何将数据从一个活动(意图)发送到另一个活动?

我使用此代码发送数据:

Intent i=new Intent(context,SendMessage.class);
i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);

当前回答

只是一个建议:

在你的i.putExtra(“id”…..)中不使用“id”或“name”,我建议在有意义的时候,使用当前可以与putExtra一起使用的标准字段,即Intent.EXTRA_shing。

完整的列表可以在Intent(Android开发者)上找到。

其他回答

我们可以通过简单的方法做到这一点:

在FirstActivity中:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);

在SecondActivity中:

    try {
        Intent intent = getIntent();

        String uid = intent.getStringExtra("uid");
        String pwd = intent.getStringExtra("pwd");

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("getStringExtra_EX", e + "");
    }

从意图中获取不同类型的额外信息

要从Intent访问数据,您应该知道两件事。

钥匙数据的DataType。

Intent类中有不同的方法来提取不同类型的数据。看起来像这样

getIntent().XXX(KEY)或intent.XXX(KEY);

因此,如果您知道在otherActivity中设置的变量的数据类型,则可以使用相应的方法。

从Intent检索活动中的字符串的示例

String profileName = getIntent().getStringExtra("SomeKey");

不同数据类型的方法的不同变体列表

您可以在意向正式文档中查看可用方法列表。

这是针对适配器的,对于您只需要更改mContext的活动对于片段,您需要将mContext更改为获取活动()

 public static ArrayList<String> tags_array ;// static array list if you want to pass array data

      public void sendDataBundle(){
            tags_array = new ArrayList();
            tags_array.add("hashtag");//few array data
            tags_array.add("selling");
            tags_array.add("cityname");
            tags_array.add("more");
            tags_array.add("mobile");
            tags_array.add("android");
            tags_array.add("dress");
            Intent su = new Intent(mContext, ViewItemActivity.class);
            Bundle bun1 = new Bundle();
            bun1.putString("product_title","My Product Titile");
            bun1.putString("product_description", "My Product Discription");
            bun1.putString("category", "Product Category");
            bun1.putStringArrayList("hashtag", tags_array);//to pass array list 
            su.putExtras(bun1);
            mContext.startActivity(su);
        }

在接收活动中

Bundle extras = getIntent().getExtras(); 
String userName;

if (extras != null) {
    userName = extras.getString("name");
    // and get whatever type user account id is
}

如果在FragmentActivity中使用,请尝试以下操作:

第一页扩展了FragmentActivity

Intent Tabdetail = new Intent(getApplicationContext(), ReceivePage.class);
Tabdetail.putExtra("Marker", marker.getTitle().toString());
startActivity(Tabdetail);

在片段中,您只需要首先调用getActivity(),

第二页扩展片段:

String receive = getActivity().getIntent().getExtras().getString("name");