user3091531 user3091531 - 5 months ago 31
Java Question

Refreshing Activity ,activity is starting from fragment

I have a fragment class which starts another activity when list item is clicked.

Intent in = new Intent(getActivity(),SResponses.class);
startActivity(in);


this activity has a handler which refresh the activity after few seconds .

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
startActivity(getIntent());
}
}, 4000);


But when once this class is opened it keep on refreshing all the time even when I press the back button it don't go back and and it keep on refreshing again and again.I want to only run this handler when this activity is active.

Answer

It is very strange approach for me to "refresh" activity like that but you can try something like this:

1) declare class members:

private Handler handler;
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
                     finish();
                     startActivity(getIntent());
    }
}

2) set handler:

handler = new Handler();
handler.postDelayed(runnable, 4000);

3) and onStop() or onDestroy() call `handler.removeCallbacks(runnable);