I have an activity, say A
, which has a fragment with a textview called TotalTimerFragment
which contains a countdowntimer
. There are 2 other fragments called F1
and F2
. Activity A
adds F1
and the countdowntimer
in fragment TotalTimerFragment
starts. After a few seconds F1
is replaced by F2
. And here the countdowntimer
should continue for few more seconds. But it crashes and gives a NullPointerException
for the findViewById in the OnTick method in the class.
Here is the code for the FT fragment: getActivity().findViewById(R.id.total_timer_textview)
in onTick
method gives NullPointerException
public class TotalTimerFragment extends Fragment{
TextView totalWorkoutTimer;
TotalTimeCounter timeCounter;
static long total_millis;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_totaltimer, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
totalWorkoutTimer = (TextView) getActivity().findViewById(R.id.total_timer_textview);
}
public class TotalTimeCounter extends CountDownTimer {
TextView totalWorkoutTimer;
public TotalTimeCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
total_millis = millisUntilFinished;
String total_hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(total_millis),
TimeUnit.MILLISECONDS.toMinutes(total_millis) - TimeUnit.HOURS.toMinutes(TimeUnit.
MILLISECONDS.toHours(total_millis)), TimeUnit.MILLISECONDS.toSeconds(total_millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(total_millis)));
totalWorkoutTimer = (TextView)getActivity().findViewById(R.id.total_timer_textview);
totalWorkoutTimer.setText(total_hms);
}
@Override
public void onFinish() {
}
}
}