简体   繁体   中英

How can I pass json data from onPostExecute to a fragment?

In my work i need to pass Json data from my onPostExecute() to a class that extends fragment . I have tried a lot by the following way but I am unable to get desired output....Please help me . Here below code is from my onPostExecute() :

else if(boollatlon==true){
        json_string=s;
        Intent intent=new Intent(context,MapFragment.class);
        //MapFragment.class is that class that extends Fragment
        intent.putExtra("json_data",json_string);
        context.startActivity(intent);
    }

Here below is my MapFragment class :

public class MapFragment extends Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_map_fragment,container,false);
    return view;
}

}

您可以在下一个代码中的onCreateView中调用该片段:

String jsonData = getActivity().getIntent().getStringExtra("json_data");

When I see such a scenario, I think your best friend would be using Events. There are robust libraries like EventBus - my favorite.

You can add to your build.gradle file like this:

 compile 'org.greenrobot:eventbus:3.0.0'

You can then create a simple plain old java object like this:

(I assume you are fetching your information from somewhere and that is why you have an AsyncTask)

public class FetchCompletedEvent{
    public String json;

    public FetchCompletedEvent(String json){
        this.json = json;
    }
}

Now, inside your onPostExecute method, you can notify the fragment of the event completion by using EventBus like this:

//inside onPostExecute()
String jsonString = result;
EventBus.getDefault().post(new FetchCompletedEvent(jsonString));

That is it for that part. Next is in your fragment class, do this:

//inside onAttach or onCreate of your fragment;
EventBus.getDefault().register(this);

//now override onEvent method to handle the json String you will be given by the event

public void onEvent(FetchCompletedEvent event){

    //you could consider using a getter in your event class for this
    String json = event.json;
    //now you can update your UI with the new JSON data
}

//finally, unregister inside onDestroy
@Override public void onDestroy(){
    super.onDestroy()
    EventBus.getDefault().unregister(this);
}

That, is all you need to pass your data to your fragment from inside onPostExecute method of your AsyncTask.

Events help decouple your code and eliminates too many dependencies - one of OOP grand principles!

I hope this helps! Good luck and happy coding!

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