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

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

    I use Gson with its so powerful and simple api to send objects between activities,

    Example

    // This is the object to be sent, can be any object
    public class AndroidPacket {
    
        public String CustomerName;
    
       //constructor
       public AndroidPacket(String cName){
           CustomerName = cName;
       }   
       // other fields ....
    
    
        // You can add those functions as LiveTemplate !
        public String toJson() {
            Gson gson = new Gson();
            return gson.toJson(this);
        }
    
        public static AndroidPacket fromJson(String json) {
            Gson gson = new Gson();
            return gson.fromJson(json, AndroidPacket.class);
        }
    }
    

    2 functions you add them to the objects that you want to send

    Usage

    Send Object From A to B

        // Convert the object to string using Gson
        AndroidPacket androidPacket = new AndroidPacket("Ahmad");
        String objAsJson = androidPacket.toJson();
    
        Intent intent = new Intent(A.this, B.class);
        intent.putExtra("my_obj", objAsJson);
        startActivity(intent);
    

    Receive In B

    @Override
    protected void onCreate(Bundle savedInstanceState) {        
        Bundle bundle = getIntent().getExtras();
        String objAsJson = bundle.getString("my_obj");
        AndroidPacket androidPacket = AndroidPacket.fromJson(objAsJson);
    
        // Here you can use your Object
        Log.d("Gson", androidPacket.CustomerName);
    }
    

    I use it almost in every project i do and I have no performance issues.

提交回复
热议问题