I used this for getting Date and Time in a fragment.
private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_head_screen, container, false);
dateTextView = root.findViewById(R.id.dateView);
hourTv = root.findViewById(R.id.hourView);
Thread thread = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
mHandler.post(new Runnable() {
@Override
public void run() {
//Calendario para obtener fecha & hora
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");
String currentDate = date_sdf.format(currentTime);
String currentHour = hour_sdf.format(currentTime);
dateTextView.setText(currentDate);
hourTv.setText(currentHour);
}
});
}
} catch (InterruptedException e) {
Log.v("InterruptedException", e.getMessage());
}
}
};
}