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

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

    This question is also discussed in another Stack Overflow question. Please have a look at a solution to Passing data through intent using Serializable. The main point is about using Bundle object which stores the necessary data inside Intent.

     Bundle bundle = new Bundle();
    
     bundle.putSerializable(key1, value1);
     bundle.putSerializable(key2, value2);
     bundle.putSerializable(key3, value3);
    
     intent.putExtras(bundle);
    

    To extract values:

     Bundle bundle = new Bundle();
    
     for (String key : bundle.keySet()) {
     value = bundle.getSerializable(key));
     }
    

    Advantage of Serializable is its simplicity. However, you should consider using Parcelable method if you need many data to be transferred, because Parcelable is specifically designed for Android and it is more efficient than Serializable. You can create Parcelable class using:

    1. an online tool - parcelabler
    2. a plugin for Android Studio - Android Parcelable code generator

提交回复
热议问题