xyzio

Passing a datastructure between Android activities as JSON

leave a comment »

Passing a data structure between Android activities as JSON using Gson.

In the sending Activity:

//Data
Droplet data = new Droplet();
//Create intent
Intent intent = new Intent(SendingClass.this, ReceivingClass.class);
//Create JSON object from data structure
Gson gson = new Gson();
String json = gson.toJson(data);
//Add JSON to intent
intent.putExtra("json", json);
//Start Activity with intent
startActivity(intent);

In the receiving Activity:

//Get string
String json = extras.getString("json","-1");
//Convert JSON to class
Gson gson = new Gson();
Droplet droplet = gson.fromJson(json, Droplet.class);

Where Droplet is defined here.

Written by M Kapoor

September 26, 2014 at 5:13 pm

Posted in java

Leave a comment