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

后端 未结 30 3961
遇见更好的自我
遇见更好的自我 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:47

    Create two methods in your custom Class like this

    public class Qabir {
    
        private int age;
        private String name;
    
        Qabir(){
        }
    
        Qabir(int age,String name){
            this.age=age; this.name=name;
        }   
    
        // method for sending object
        public String toJSON(){
            return "{age:" + age + ",name:\"" +name +"\"}";
        }
    
        // method for get back original object
        public void initilizeWithJSONString(String jsonString){
    
            JSONObject json;        
            try {
                json =new JSONObject(jsonString );
                age=json.getInt("age");
                name=json.getString("name");
            } catch (JSONException e) {
                e.printStackTrace();
            } 
        }
    }
    

    Now in your sender Activity do like this

    Qabir q= new Qabir(22,"KQ");    
    Intent in=new Intent(this,SubActivity.class);
    in.putExtra("obj", q.toJSON());
    startActivity( in);
    

    And in your receiver Activity

    Qabir q =new Qabir();
    q.initilizeWithJSONString(getIntent().getStringExtra("obj"));
    

提交回复
热议问题