1

I have a fragment that gets data from a DialogFragment via intent with onActivityResult(...);

I am trying to update the fragment's UI but runOnUiThread does not work.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    ArrayList<Farm> farms = data.getParcelableArrayListExtra("farms_list");
    float totalArea = 0;
    for(Farm farm : farms) {
        if (farm.isSelected()) {
            Log.d("farm", farm.getName());
            totalArea += farm.getArea();
        }
    }
    final float finalTotalArea = totalArea;
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            area.setText(String.valueOf(finalTotalArea));
        }
    });
}

The area TextView does not update.

I get the reference to the activity with onAttach() method.

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (!(context instanceof PageFragmentCallbacks)) {
        throw new ClassCastException(
                "Activity must implement PageFragmentCallbacks");
    }

    mCallbacks = (PageFragmentCallbacks) context;
    this.activity = (Activity) context;
}
Manos
  • 1,471
  • 1
  • 28
  • 45

3 Answers3

0

onActivityResult is being called on main thread. More here. For some reason views can't be edited from this method (probably not created or drawn). One trick that you can do is set var boolean updateTextView = false; On onActivityResult set it on true, save data that you got, and than onResume check updateTextView and if true set data to your TextView.

Vladimir Jovanović
  • 2,261
  • 2
  • 24
  • 43
0

What about trying to wrap it in a proper thread that you launch afterwards?

new Thread() {
            public void run() {
                try {
                   activity.runOnUiThread(new Runnable() {
                       @Override
                       public void run() {
                          area.setText(String.valueOf(finalTotalArea));
                       }
                   });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();
Amesys
  • 816
  • 2
  • 10
  • 19
0

Seems like your Activity is loosing your Fragment somewhere, what I did in this case was to add a Method to my Callbacks, maybe reattachDialog(DialogFragment dialogFragment) and calling it in onResume of the DialogFragment with reattachDialog(this).

And in your Activity you do this:

@Override
public void reattachFragment(DialogFragment dialogFragment) {
 this.dialogFragment = dialogFragment;
}

Or in Fragment:

@Override
public void reattachFragment(DialogFragment dialogFragment) {
 getActivity().setDialog(dialogFragment);
}
David
  • 306
  • 6
  • 20