Auto refresh android fragment until condition is met

Viewed 74

I'm building a multi-fragment app for android. I'm now executing in my third fragment, and I'm trying to get it to auto refresh until a timer reaches 0, after which it should open the next fragment and transition. Someone suggested I use the following to auto-refresh, but upon the condition being met, the app closes and Android tells me it stopped working. The 4th fragment isn't shown at all.

This is the way I am refreshing in my code, in the onCreateView() for my 3rd fragment:

refresh = new Runnable() {
    @Override
    public void run() {
        if (isRunning) {
            // do some stuff here
            handler.postDelayed(refresh, 500);
        } else
            return;
    }
};
handler.post(refresh);

I am making calls to the UI in the refresh run() since I am updating multiple textviews. Should I make a seperate thread for this?

1 Answers

To refresh fragment in android use the following code.
Fragment refreshing method

public void refreshFragment(){
    Fragment currentFragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.container);
    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
    fragmentTransaction.detach(currentFragment); 
    fragmentTransaction.attach(currentFragment);
    fragmentTransaction.commit();
}

You can place it in a handler and invoke the method whenever needed.
Note: Make sure to call method inside

runOnUiThread(new Runnable{//code here})

Related