2

I want to transfer from one Activity to another an ArrayList through the intent. How can I do that, since I can't make the JSONObject class to implement parcelable

Libathos
  • 3,340
  • 5
  • 36
  • 61

2 Answers2

5

You can simply put an entire JSONObject as a string.

intent.putString("YOUR_KEY", jsonObj.toString);

And then in the SecondActivity you can convert the Json String into JsonObject

JSONObject jsonObj = new JSONObject(getIntent().getStringExtra("YOUR_KEY"));

You can Create a ArrayList i.e json.ToString()

JSONObject json1 = null,json2 = null;
ArrayList<String> jsonList=new ArrayList<String>();
jsonList.add(json1.toString());
jsonList.add(json2.toString());
i.putStringArrayListExtra("json_list", jsonList);

And then in the SecondActivity you can convert the Json String into JsonObject

JSONObject jsonObj1 = new JSONObject(getIntent().getStringExtra("json_list").get(0));
JSONObject jsonObj2 = new JSONObject(getIntent().getStringExtra("json_list").get(1));
Amit Gupta
  • 8,914
  • 1
  • 25
  • 33
-1

To change from one Activity to another, you need an intent. And you can put extra info to this intent. Not all types are available, but String is*:

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);

*You can find more info at: Passing a Bundle on startActivity()?

As you may know, you can transform an ArrayList to a JSONArray and this last one can be serialized as a string**:

ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("baar");
JSONArray jsArray = new JSONArray(list);

**You can find more info at: convert ArrayList<MyCustomClass> to JSONArray

Now you only need to put your array-string to your intent and parse it again on your recently opened class***:

String value = getIntent().getExtras().getString(key);

***More info at the first link

Community
  • 1
  • 1
Alex Cabrera
  • 373
  • 1
  • 9
  • Ok but then how can I transform my String into ArrayList ? – Libathos Oct 15 '13 at 16:16
  • should be something like new JSONArray(value). Then you have a JSONArray and from there you can then get the objects inside – Mario Lenci Oct 15 '13 at 16:27
  • @libathos, on the last step, you have an string that has a JSONArray of JSONObjects json-encoded. You just need to parse the json string and "re-mount" your ArrayList... It's a simple JSON routine. Check my answer on this link where a user doesn't know how to parse a JSON to put it in a ListView, the parsing part is similar to what you need to do http://stackoverflow.com/questions/19179610/google-api-parsing-in-json/19180887#19180887 – Alex Cabrera Oct 15 '13 at 17:16
  • mBundle.extras - wrong mIntent.putExtras(mBundle); - Where is the key? – LEE Sep 08 '17 at 08:08