John David
John David

Reputation: 334

Intent JSONObject to another activity

I want to pass JSONObject to another activity in the else section in he below code so i can use profile details in the other 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();
    }
}

Upvotes: 2

Views: 3029

Answers (4)

Blackbelt
Blackbelt

Reputation: 157467

to pass a JSONObject you can use a String. For instance:

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

toString() implementation of the JSONObject, class rncodes the object as a compact JSON string. In your RegisterActivity, to retrieve the String:

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

Upvotes: 5

Simar
Simar

Reputation: 590

You can use global data

public class GlobalData extends Application{
    JSONObject jsonObj;
}

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

You also need to declare in manifest in application tag android:name=".GlobalData"

Upvotes: -1

Kody
Kody

Reputation: 1254

Blackbelt is right, but another valid solution is to use a simple object implementing Parcelable

e.g.

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

Upvotes: 0

Vilas
Vilas

Reputation: 1705

You can not pass objects easily to another activity, if the object is not parcelable. To achieve this, you can create a class. For example name it, RunTimeData.

In this class create a static JSONObject.

public class RunTimeData{
    public static JSONObject object;
}

So whenever you want to store the data, you can store it as follows.

RunTimeData.object=result;

When you want to use this, in another activity use,

JSONObject result=RunTimeData.object.

And finally when you are sure that you are not going to use this value anymore in the program, null it.

RunTimeData.object=null;

Upvotes: 0

Related Questions