modabeckham
modabeckham

Reputation: 247

Accessing the json response from another activty

I have a fragment and I'm accessing a API inside onCreate() in the fragment, then the I'm getting the json response to the same fragment class (which is returned from the onPostExecute() in AsyncTask class). Now I'm receiving the json response inside the onTaskCompleted() as shown below,

@Override
    public void onTaskCompleted(JSONArray responseJson) {
        try {
            for (int i = 0; i < responseJson.length(); ++i) {
                final JSONObject object = responseJson.getJSONObject(i);
                ...

My problem is I have an activity and I want to get these data to that activity. How can I access these data?

Is it possible for me to do something like,

mdata = fragment.onTaskCompleted();

Any help would be highly appreciated.

UPDATED

There is no direct contact between the activity and fragment. Because I'm not using intent. Fragment is the menu and I'm loading data there. Activity is used for search. I'm trying to get that already loaded data to search activity.

Upvotes: 0

Views: 398

Answers (5)

Karthika PB
Karthika PB

Reputation: 1373

You can do this in different ways 1) you can read the json data and store it in a hash map and pass it to that activity. 2) You can pass the same json string to other activity using intent and read data from json there. 3) You can store the Json string in a static string variable of your project and can access the same inside the activity(this's is not fair for crucial apps but is easy)

like

create a class Constantss.java and declare

public static String myjson="";

then inside your class onTaskcomplete

@Override
    public void onTaskCompleted(JSONArray responseJson) {
        try {

 Constantss. myjson=responseJson.toString();
            for (int i = 0; i < responseJson.length(); ++i) {
                final JSONObject object = responseJson.getJSONObject(i);
....
}

inside fragment

String js;
if(Constantss.myjson.length()>0)
 js=Constantss.myjson; //this is the json string convert i to jsonarray and use

Upvotes: 1

SilentKnight
SilentKnight

Reputation: 14021

If you don't mean to use this json data, you can not deal with it. You just need to pass this json in String to the second Activity in which you handle these data if you need to do.
So, codes may be like this:

@Override
public void onTaskCompleted(JSONArray responseJson) {
    if( responsejson != null ){
        String json = responsejson.toString();
        Intent intent = new Intent(getActivity(), SecondActivity.class);
        intent.putExtra("json", json);
        startActivity(intent);


And in the second Activity, you just need to convert the json String into Json data again, just like this maybe:

String json = getIntent().getString("json");
JsonArray jsonArray = new JsonArray(json);
try {
    for (int i = 0; i < jsonArray.length(); ++i) {
        final JSONObject object = jsonArray.getJSONObject(i);
        ...

Upvotes: 0

ABeade
ABeade

Reputation: 1

You can communicate one fragment with its owner activity defining and interface with a listener, implementing this interface on the activity, and calling the listener from the fragment, as it is proposed on the official documentation: Communicating with Other Fragments

Another good option for me is use an event bus like greenrobot/EventBus

Upvotes: 0

Ashish Tamrakar
Ashish Tamrakar

Reputation: 820

You can pass data from Fragment to Activity using interfaces, here's a very simple example -

public class Fragment2 extends Fragment {

  public interface onSomeEventListener {
    public void someEvent(String s);
  }

  onSomeEventListener someEventListener;

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
        try {
          someEventListener = (onSomeEventListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement onSomeEventListener");
        }
  }

  final String LOG_TAG = "myLogs";

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment2, null);

    Button button = (Button) v.findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        someEventListener.someEvent("Test text to Fragment1");
      }
    });

    return v;
  }
}

inside your Activity -

    public class MainActivity extends Activity implements onSomeEventListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Fragment frag2 = new Fragment2();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.fragment2, frag2);
        ft.commit();
    }

  @Override
  public void someEvent(String s) {
      Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1);
      ((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s);
  }
}

Hope this helps :)

Upvotes: 0

Fahim
Fahim

Reputation: 12378

You can simply put an entire JSONObject as a string. Something like this:

i.putString("product", jsonObj.toString);

And then in the SecondtActivity you could

JSONObject jsonObj = new JSONObject(getIntent().getStringExtra("product"));

Upvotes: 1

Related Questions