How do I get extra data from intent on Android?

2018-12-31 02:13发布

How can I send data from one activity (intent) to another?

I use this code to send data:

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

16条回答
泪湿衣
2楼-- · 2018-12-31 02:40

I just posted an answer here that covers this topic in a bit more detail, including some alternatives.

It utilises Vapor API, a new jQuery inspired Android framework I wrote to simplify Android dev. Check out the example in that answer for how you can easily pass data between activites.

Also it demonstrates VaporIntent, which lets you chain method calls and utilise the overloaded .put(...) method:

$.Intent().put("data", "myData").put("more", 568)...

You can easily pass data around your whole application using Vapor API, so hopefully it'll be helpful to you and others during app development.

查看更多
步步皆殇っ
3楼-- · 2018-12-31 02:41

First, get the intent which has started your activity using the getIntent() method:

Intent intent = getIntent();

If your extra data is represented as strings, then you can use intent.getStringExtra(String name) method. In your case:

String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");
查看更多
ら面具成の殇う
4楼-- · 2018-12-31 02:41

You can also do like this
// put value in intent

    Intent in = new Intent(MainActivity.this, Booked.class);
    in.putExtra("filter", "Booked");
    startActivity(in);

// get value from intent

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    String filter = bundle.getString("filter");
查看更多
ら面具成の殇う
5楼-- · 2018-12-31 02:46

We can do it by simple means:

In FirstActivity:

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

In 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 + "");
    }
查看更多
登录 后发表回答