Search code examples
javaandroidandroid-fragmentsasynchronousandroid-fragmentactivity

Sending data from Activity to Fragment from internet


I have a Class which contains 3 Fragment all data needs to be gathered from the same URL. I run a nested Async Class(in Activity) to get data from URL and then I store that data in the bundle for each fragment like.

 Bundle bundle = new Bundle();
        bundle.putString("edttext", json.toString());
        InfoFragment fragobj = new InfoFragment();
        fragobj.setArguments(bundle);

Before i was Calling the Async Class in Fragment itself and everything was working fine,but now added two more fragments so to reduce number of URL requests, am calling Async class from Activity class and distribute data to my 3 fragment class.

Issue:Fragment is called before the bundle was set asynchronously and showing null bundle in fragment.


Solution

  • You can Broadcast Intent from the parent activity after you get the response in the onPostExeceute() of AsyncTask

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        Intent intent = new Intent("key_to_identify_the_broadcast");
        Bundle bundle = new Bundle();
        bundle.putString("edttext", json.toString());
        intent.putExtra("bundle_key_for_intent", bundle);
        context.sendBroadcast(intent);
    }
    

    and then you can receive the bundle in your fragment by using the BroadcastReceiver class

    private final BroadcastReceiver mHandleMessageReceiver = new 
    BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = 
                intent.getExtras().getBundle("bundle_key_for_intent");
                if(bundle!=null){
                    String edttext = bundle.getString("edttext");
                }
                //you can call any of your methods for using this bundle for your use case
        }
    };
    

    in onCreateView() of your fragment you need to register the broadcast receiver first otherwise this broadcast receiver will not be triggered

    IntentFilter filter = new IntentFilter("key_to_identify_the_broadcast");
    getActivity().getApplicationContext().
                   registerReceiver(mHandleMessageReceiver, filter);
    

    Finally you can unregister the receiver to avoid any exceptions

    @Override
    public void onDestroy() {
        try {
    
             getActivity().getApplicationContext().
                 unregisterReceiver(mHandleMessageReceiver);
    
        } catch (Exception e) {
            Log.e("UnRegister Error", "> " + e.getMessage());
        }
        super.onDestroy();
    }
    

    You can create separate broadcast receivers in all of your fragments and use the same broadcast to broadcast the data to all of your fragments. You can also use different keys for different fragments and then broadcast using particular key for particular fragment.