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

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

    If you have a singleton class (fx Service) acting as gateway to your model layer anyway, it can be solved by having a variable in that class with getters and setters for it.

    In Activity 1:

    Intent intent = new Intent(getApplicationContext(), Activity2.class);
    service.setSavedOrder(order);
    startActivity(intent);
    

    In Activity 2:

    private Service service;
    private Order order;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quality);
    
        service = Service.getInstance();
        order = service.getSavedOrder();
        service.setSavedOrder(null) //If you don't want to save it for the entire session of the app.
    }
    

    In Service:

    private static Service instance;
    
    private Service()
    {
        //Constructor content
    }
    
    public static Service getInstance()
    {
        if(instance == null)
        {
            instance = new Service();
        }
        return instance;
    }
    private Order savedOrder;
    
    public Order getSavedOrder()
    {
        return savedOrder;
    }
    
    public void setSavedOrder(Order order)
    {
        this.savedOrder = order;
    }
    

    This solution does not require any serialization or other "packaging" of the object in question. But it will only be beneficial if you are using this kind of architecture anyway.

提交回复
热议问题