Intent JSONObject 到另一个 activity

Intent JSONObject to another activity

我想在下面代码的 else 部分将 JSONObject 传递给另一个 activity,这样我就可以在另一个 activity、

中使用配置文件详细信息
public void redirectToActivity(JSONObject result, JSONObject profile){

    try {           
        String status = result.getString("status");

        if (status.equals("204")) {
            Intent intent = new Intent(this, ActivityMenu.class);
            intent.putExtra("user", "email");
            this.startActivity(intent);
        } 
        else {
            Intent intent = new Intent(this, RegisterActivity.class);
            this.startActivity(intent);
            //here I want to pass JSONObject profile to RegisterActivity
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

要传递 JSONObject,您可以使用 String。例如:

 Intent intent = new Intent(this, RegisterActivity.class);
 intent.putExtra("profile", profile.toString());
 intent.putExtra("result", result.toString());
 this.startActivity(intent);

toString() JSONObject 的实现,class 将对象编码为紧凑的 JSON 字符串。在您的 RegisterActivity 中检索字符串:

 String profile = getIntent().getStringExtra("profile");
 JSONObject profileJSON = new JSONObject(profile)

如果对象不可分割,则您无法轻松地将对象传递给另一个 activity。为此,您可以创建一个 class。例如将其命名为 RunTimeData.

在此 class 创建一个静态 JSONObject。

public class RunTimeData{
    public static JSONObject object;
}

所以每当你想存储数据时,你可以按如下方式存储。

RunTimeData.object=result;

当你想用这个的时候,在另一个activity中使用,

JSONObject result=RunTimeData.object.

最后,当您确定您不会再在程序中使用该值时,将其置空。

RunTimeData.object=null;

Blackbelt 是对的,但另一个有效的解决方案是使用一个简单的对象实现 Parcelable

例如

MyObject obj = new MyObject();
obj.setTitle(myJsonObject.getJSONObject("title").opt("val").toString());
...
intent.putExtra("someCoolTAG", obj);

您可以使用全局数据

public class GlobalData extends Application{
    JSONObject jsonObj;
}

else{
    ((GlobalData)getApplication).jsonObj = myJsonObj;
    startActivity(new Intent(...));
}

你还需要在应用标签的manifest中声明 android:name=".GlobalData"