I have an Activity which uses a Fragment. I simply want to pass an JSONObject from this Activity to the Fragment.How could I do it?
            Asked
            
        
        
            Active
            
        
            Viewed 1,665 times
        
    -3
            
            
        - 
                    2Possible duplicate of [Passing an Object from an Activity to a Fragment](http://stackoverflow.com/questions/9931993/passing-an-object-from-an-activity-to-a-fragment) – Nongthonbam Tonthoi May 18 '16 at 09:02
- 
                    I think you can convert the JSON object into toString pass from activity to fragment and make the json object from string in your fragment – Bhavdip Sagar May 18 '16 at 09:03
3 Answers
1
            
            
        Do this: lets say this is the jsonObject: JSONObject obj=...; to add your fragment, do this:
<Your_fragment_name> myFrag=<Your_fragment_name>();
    Bundle bundle=new Bundle();
    bundle.putString("key",obj.toString());
    Frag frag=new Frag();
    frag.setArguments(bundle);
    getSupportFragmentManager().beginTransaction().replace(<your_container_id>,myFrag).commit();
then in your fragment's onCreateView() add this to get the json back
 Bundle bundle=getArguments();
    String jsonString=bundle.getString("key");
    JSONObject obj;
    try {
        obj=new JSONObject(jsonString);
    } catch (JSONException e) {
        e.printStackTrace();
    }
 
    
    
        NezSpencer
        
- 640
- 8
- 12
0
            
            
        If you have data in your activity, then you can get that from fragment. Try to convert JSON to string using toString(), then get that string from fragment.
 
    
    
        Alvin
        
- 894
- 8
- 16
- 
                    I didn't use Android SDK from a long time but I believe that you can add Object to the intent, just put the JSONObject into the intent et recover it on the other side (with some casting) – AxelH May 18 '16 at 09:05
0
            
            
        You can make the JSON object public in the activity and then you can access it in your fragment by using
getActivity().jsonObject
 
    
    
        Ruben2112
        
- 423
- 4
- 18
