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

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

    Another way to do this is to use the Application object (android.app.Application). You define this in you AndroidManifest.xml file as:

    You can then call this from any activity and save the object to the Application class.

    In the FirstActivity:

    MyObject myObject = new MyObject();
    MyApplication app = (MyApplication) getApplication();
    app.setMyObject(myObject);
    

    In the SecondActivity, do :

    MyApplication app = (MyApplication) getApplication();
    MyObject retrievedObject = app.getMyObject(myObject);
    

    This is handy if you have objects that have application level scope i.e. they have to be used throughout the application. The Parcelable method is still better if you want explicit control over the object scope or if the scope is limited.

    This avoid the use of Intents altogether, though. I don't know if they suits you. Another way I used this is to have int identifiers of objects send through intents and retrieve objects that I have in Maps in the Application object.

提交回复
热议问题