Skip to content Skip to sidebar Skip to footer

Send Data From Service To Fragment, Android

Good evening! I have small problem with Service. At first, I have fragment with several TextViews. Into these TextView I want put text from my Service. And this code of my simple

Solution 1:

Simply broadcast the result from your service and receive it in your fragment through a Broadcast Receiver

You could, for example, broadcast your exercises in the onPostExecute like this

@OverrideprotectedvoidonPostExecute(String strJson) {
        super.onPostExecute(strJson);
        Log.d(LOG_TAG, strJson + " " + url);
        exercises = ParseJSON.ChallengeParseJSON(strJson);
        Log.d("Challenges", "challenges: " + exercises.get(0).getName() + " " + exercises.get(1).getName());

        Intent intent = newIntent(FILTER); //FILTER is a string to identify this intent
        intent.putExtra(MY_KEY, exercises); 
        sendBroadcast(intent);
    }

However, Your Exercise object needs to be parcelable for this to work smoothly. Or you could just broadcast your raw json string and call your ParseJSON.ChallengeParseJSON(strJson); in your fragment

Then in your Fragment you create a receiver

privateBroadcastReceiverreceiver=newBroadcastReceiver() {

@OverridepublicvoidonReceive(Context context, Intent intent) {
  ArrayList<Exercises> exercises = intent.getExtras().get(MY_KEY);

  //or//exercises = ParseJSON.ChallengeParseJSON(intent.getStringExtra(MY_KEY));

   }
};

and register it in your onResume

@Override
 protected void onResume() {
   super.onResume();
   getActivity().registerReceiver(receiver, new IntentFilter(FILTER));
 }

You also need to unregister it in your onPause using getActivity().unregisterReceiver(receiver);

You can also read more about it here if interested

Solution 2:

You can do it by 2 methods.

  1. Save data to database and get data in fragment.
  2. Use Broadcast

Post a Comment for "Send Data From Service To Fragment, Android"