How to send objects through bundle

前端 未结 11 1250
我寻月下人不归
我寻月下人不归 2020-11-27 13:15

I need to pass a reference to the class that does the majority of my processing through a bundle.

The problem is it has nothing to do with intents or contexts and ha

11条回答
  •  情歌与酒
    2020-11-27 13:20

    You can also use Gson to convert an object to a JSONObject and pass it on bundle. For me was the most elegant way I found to do this. I haven't tested how it affects performance.

    In Initial Activity

    Intent activity = new Intent(MyActivity.this,NextActivity.class);
    activity.putExtra("myObject", new Gson().toJson(myobject));
    startActivity(activity);
    

    In Next Activity

    String jsonMyObject;
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
       jsonMyObject = extras.getString("myObject");
    }
    MyObject myObject = new Gson().fromJson(jsonMyObject, MyObject.class);
    

提交回复
热议问题