How to send an object from one Android Activity to another using Intents?

后端 未结 30 3603
-上瘾入骨i
-上瘾入骨i 2020-11-21 04:47

How can I pass an object of a custom type from one Activity to another using the putExtra() method of the class Intent?

30条回答
  •  感动是毒
    2020-11-21 05:08

    Start another activity from this activity pass parameters via Bundle Object

    Intent intent = new Intent(getBaseContext(), YourActivity.class);
    intent.putExtra("USER_NAME", "xyz@gmail.com");
    startActivity(intent);
    

    Retrieve on another activity (YourActivity)

    String s = getIntent().getStringExtra("USER_NAME");
    

    This is ok for simple kind data type. But if u want to pass complex data in between activity u need to serialize it first.

    Here we have Employee Model

    class Employee{
        private String empId;
        private int age;
        print Double salary;
    
        getters...
        setters...
    }
    

    You can use Gson lib provided by google to serialize the complex data like this

    String strEmp = new Gson().toJson(emp);
    Intent intent = new Intent(getBaseContext(), YourActivity.class);
    intent.putExtra("EMP", strEmp);
    startActivity(intent);
    
    Bundle bundle = getIntent().getExtras();
        String empStr = bundle.getString("EMP");
                Gson gson = new Gson();
                Type type = new TypeToken() {
                }.getType();
                Employee selectedEmp = gson.fromJson(empStr, type);
    

提交回复
热议问题