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

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

    Use gson to convert your object to JSON and pass it through intent. In the new Activity convert the JSON to an object.

    In your build.gradle, add this to your dependencies

    implementation 'com.google.code.gson:gson:2.8.4'
    

    In your Activity, convert the object to json-string:

    Gson gson = new Gson();
    String myJson = gson.toJson(vp);
    intent.putExtra("myjson", myjson);
    

    In your receiving Activity, convert the json-string back to the original object:

    Gson gson = new Gson();
    YourObject ob = gson.fromJson(getIntent().getStringExtra("myjson"), YourObject.class);
    

    For Kotlin it's quite the same

    Pass the data

    val gson = Gson()
    val intent = Intent(this, YourActivity::class.java)
    intent.putExtra("identifier", gson.toJson(your_object))
    startActivity(intent)
    

    Receive the data

    val gson = Gson()
    val yourObject = gson.fromJson(intent.getStringExtra("identifier"), YourObject::class.java)
    

提交回复
热议问题