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;
}
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.
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();
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);
}
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.