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

后端 未结 30 3575
-上瘾入骨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:19

    Using google's Gson library you can pass object to another activities.Actually we will convert object in the form of json string and after passing to other activity we will again re-convert to object like this

    Consider a bean class like this

     public class Example {
        private int id;
        private String name;
    
        public Example(int id, String name) {
            this.id = id;
            this.name = name;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    We need to pass object of Example class

    Example exampleObject=new Example(1,"hello");
    String jsonString = new Gson().toJson(exampleObject);
    Intent nextIntent=new Intent(this,NextActivity.class);
    nextIntent.putExtra("example",jsonString );
    startActivity(nextIntent);
    

    For reading we need to do the reverse operation in NextActivity

     Example defObject=new Example(-1,null);
        //default value to return when example is not available
        String defValue= new Gson().toJson(defObject);
        String jsonString=getIntent().getExtras().getString("example",defValue);
        //passed example object
        Example exampleObject=new Gson().fromJson(jsonString,Example .class);
    

    Add this dependancy in gradle

    compile 'com.google.code.gson:gson:2.6.2'
    

提交回复
热议问题