Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing JSONObject to another activity via Intent

I know what to do with the method jsonObj.toString() but I have a reason to can not do so. My JSONObject has a JSONArray inside that has too much data, so If I convert it to String then transform back that I afraid of it reaches the limit of String type. So I want to pass a pure object rather than use that method. I implement Parcelable interface to do that but I got the error "java.lang.RuntimeException: Parcel: unable to marshal value"

public class MJSONObject implements Parcelable {
private JSONObject jsonObject;

public MJSONObject() {
}

public MJSONObject(JSONObject jsonObject) {
    this.jsonObject = jsonObject;
}

public void set(JSONObject jsonObject) {
    this.jsonObject = jsonObject;
}

public JSONObject get() {
    return jsonObject;
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

public static final Parcelable.Creator<MJSONObject> CREATOR = new Parcelable.Creator<MJSONObject>() {
    public MJSONObject createFromParcel(Parcel in) {
        return new MJSONObject(in);
    }

    public MJSONObject[] newArray(int size) {
        return new MJSONObject[size];
    }
};

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeValue(jsonObject);
}

private MJSONObject(Parcel in) {
    jsonObject = (JSONObject) in.readValue(JSONObject.class.getClassLoader());
}
like image 344
Slim_user71169 Avatar asked Nov 25 '14 02:11

Slim_user71169


1 Answers

You can easily pass your JSONObject by converting it in String like in some scenarios we send JSONObject with url by appending it as a String. So, Try to send it as String like:

intent.putExtra("jsonObject", jsonObject.toString());

And receive it on other side

Intent intent = getIntent();

String jsonString = intent.getStringExtra("jsonObject");

Now you have your JSON in a String named jsonString assume it as a response like when you received from Web Service and then get your JSONObject like:

JSONObject jObj = new JSONObject(jsonString);

hope you will understand what my point is :)

like image 97
Zubair Ahmed Avatar answered Oct 04 '22 22:10

Zubair Ahmed