Android/Java: How to get the ArrayList<JSONObject> from an Activity to another?

ΩlostA :

I want to get a value passed from another activity, it works well with multiple type like JSONArray, String, etc... but i could not find the way to retrieve a ArrayList value.

I tried several way like this one with no success:

      ArrayList<JSONObject> poiArr;   
        JSONArray jsonPoints;  
        try {
            poiArr = new ArrayList<JSONObject>(bundle.getSparseParcelableArray("poiArr"));  
//here is the problem 
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            jsonPoints = new JSONArray(bundle.getString("lesPoints"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

I have this error message:

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference

Any ideas?

SaadAAkash :

JSONObject is not Parcelable, or even Serializable. So the only option you're left with is to utilize JSONObject's toString() method and then rely on using putStringArrayListExtra() of Intent to pass it to the other.

On the other activity, use getExtras() of Intent to receive and convert that to JSONObject by passing the String into its constructor & loop to form the ArrayList if required.

Say, the ArrayList of JSONObject is sendingArr :

List<String> sendingListOfStrings = new ArrayList<String>();
for(int i = 0; i < sendingArr.length(); i++) {
    sendingListOfStrings.add( sendingArr.getJSONObject(i).toString() );
}

Sending from ActivityOne to ActivityTwo:

Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putStringArrayListExtra("sending_list", sendingListOfStrings);
startActivity(intent);

Then capture it = in the other:

ArrayList<JSONObject> receivingArr;
Bundle receivingListOfStrings = getIntent().getExtras();
ArrayList<String> list = receivingListOfStrings.getStringArrayList("sending_list");
for (int i = 0; i < receivingListOfStrings.length(); i++) {
    receivingArr.add( new JSONObject( receivingListOfStrings.get(i) ) );
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306682&siteId=1