How to pass an object from one activity to another on Android

后端 未结 30 4074
遇见更好的自我
遇见更好的自我 2020-11-21 04:03

I am trying to work on sending an object of my customer class from one Activity and display it in another Activity.

The code for t

30条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 04:59

    Start another activity from this activity and pass parameters via Bundle Object

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

    Retrive data on another activity (YourActivity)

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

    This is ok for simple kind of 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);
    

提交回复
热议问题