简体   繁体   中英

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());
}

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 :)

try this, you can also get object from one activity to another activity using ComplexPrefereces class

Add ComplexPreferences.java class in your project

import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;


/**
* This class helps to store class object in the shared preferences
*
*/

public class ComplexPreferences {

private static ComplexPreferences complexPreferences;
private Context context;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private static Gson GSON = new Gson();
Type typeOfObject = new TypeToken<Object>() {
}.getType();

private ComplexPreferences(Context context, String namePreferences, int mode) {
    this.context = context;
    if (namePreferences == null || namePreferences.equals("")) {
        namePreferences = "complex_preferences";
    }
    preferences = context.getSharedPreferences(namePreferences, mode);
    editor = preferences.edit();
}

public static ComplexPreferences getComplexPreferences(Context context,
                                                       String namePreferences, int mode) {

    if (complexPreferences == null) {
        complexPreferences = new ComplexPreferences(context,
                namePreferences, mode);
    }

    return complexPreferences;
}

public void putObject(String key, Object object) {
    if(object == null){
        throw new IllegalArgumentException("object is null");
    }

    if(key.equals("") || key == null){
        throw new IllegalArgumentException("key is empty or null");
    }

    editor.putString(key, GSON.toJson(object));
}

public void commit() {
    editor.commit();
}

public <T> T getObject(String key, Class<T> a) {

    String gson = preferences.getString(key, null);
    if (gson == null) {
        return null;
    } else {
        try{
            return GSON.fromJson(gson, a);
        } catch (Exception e) {
            throw new IllegalArgumentException("Object storaged with key " + key + " is instanceof other class");
        }
    }
}

}

Store object in shared preference like this:

    ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(getActivity(), "store_object", 0);
    complexPreferences.putObject("class_name", className);
    complexPreferences.commit();

For retrieving back object like this:

    ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(DrawerActivity.this, "store_object", 0);
    ClassName className=complexPreferences.getObject("class_name", ClassName.class);

Passing object as intent, serilizable is the best way. Here is the code to pass the intent from one activity

MJSONObject  mObject;
Intent intent = new Intent(FromActivity.this, ToActivity.class);
Bundle userObject = new Bundle();
userObject.putSerializable("Object", mObject);
userObject.putString("method_name", "ObjectIntent");
intent.putExtras(userObject);
startActivity(intent);

In another activity get the intent using as follows:

String method_name = null;
MJSONObject  mObject;
method_name = getIntent().getStringExtra("method_name");
if(method_name.equals("ObjectIntent"))
{
mObject= (MJSONObject) getObject.getSerializable("Object");
}

Finally your pojo class of custom object should be:

public class MJSONObject implements Serializable {

private static final long serialVersionUID = 1L;

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM