-1

In my app, I'm doing a network operation in a thread. In the result of the network operation, I show a toast and replace the fragment using the runOnUiThread() method. But the app gets hanged after the fragment is replaced.

Here is my code

getBaseActivity().runOnUiThread(() -> {
    hideProgressDialog();
    showToastAlertDialog(getString(R.string.mystring));
    MyFragment fragment = new MyFragment();
    getBaseActivity().replaceFragment(getActivity(), fragment, false, R.id.baseFragment);

BaseActivity.java

public void replaceFragment(FragmentActivity activity, Fragment fragment, boolean addToBackStack, int baseFragment) {
        try {
            FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
            ft.replace(baseFragment, fragment);
            if (addToBackStack) {
                ft.addToBackStack(null);
            }
            ft.commit();
        } catch (Exception exception) {
            CXLog.e(TAG, "Exception: " + exception.getLocalizedMessage(), exception);
        }
    }
Sufian
  • 6,405
  • 16
  • 66
  • 120
Madhan
  • 555
  • 5
  • 23

2 Answers2

2

Enable strict mode in application and check where your main thread is getting blocked.

Keyur Thumar
  • 608
  • 7
  • 19
0

Try this: getActivity().runOnUiThread(new Runnable...

It's because:

1) the implicit this in your call to runOnUiThread is referring to AsyncTask, not your fragment.

2) Fragment doesn't have runOnUiThread

Note that this just executes the Runnable if you're already on the main thread, and uses a Handler if you aren't on the main thread. You can implement a Handler in your fragment if you don't want to worry about the context of this, it's actually very easy:

http://developer.android.com/reference/android/os/Handler.html

Manikandan K
  • 911
  • 9
  • 21