android - 来自具有日期差异的firebase数据库的android倒数计时器
问题描述
我想通过从 firebase 数据库获取结束日期字符串来为 android 制作倒数计时器。当我尝试将结束日期字符串作为简单变量时,它可以工作,但是当我从 firebase 数据库中获得完全相同的日期字符串时,它不起作用或者我不知道该怎么办。这是我的代码
public class DashboardFragment extends Fragment {
private View dashboardFragment;
private DatabaseReference timeRef;
public String END_TIME="";
private TextView days, hour, minute,second;
private CountDownTimer mCountDownTimer;
private long mTimeLeftInMillis;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
dashboardFragment= inflater.inflate(R.layout.fragment_dashboard, container, false);
linear_layout_1 = dashboardFragment.findViewById(R.id.linear_layout_1);
linear_layout_2 = dashboardFragment.findViewById(R.id.linear_layout_2);
days = dashboardFragment.findViewById(R.id.days);
hour = dashboardFragment.findViewById(R.id.hour);
minute = dashboardFragment.findViewById(R.id.minute);
second = dashboardFragment.findViewById(R.id.second);
timeRef=FirebaseDatabase.getInstance().getReference().child("Time");
mTimeLeftInMillis=dateFormat();
ValueEventListener timeEvent=new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
END_TIME =snapshot.child("endTime").getValue(String.class);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
};
timeRef.addListenerForSingleValueEvent(timeEvent);
startTimer();
return dashboardFragment;
}
private long dateFormat() {
long diff=0;
SimpleDateFormat formatter=new SimpleDateFormat("dd.MM.yyyy, HH:mm");
formatter.setLenient(false);
String endTime_=END_TIME;
long endTime=0;
Date endDate;
try {
endDate=formatter.parse(endTime_);
endTime= Objects.requireNonNull(endDate).getTime();
}catch ( ParseException e){
e.printStackTrace();
}
long startTime = System.currentTimeMillis();
diff=endTime-startTime;
return diff;
}
private void startTimer() {
mCountDownTimer= new CountDownTimer(mTimeLeftInMillis, 1000) {
@Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
long Days = mTimeLeftInMillis / (24 * 60 * 60 * 1000);
long Hours = mTimeLeftInMillis / (60 * 60 * 1000) % 24;
long Minutes = mTimeLeftInMillis / (60 * 1000) % 60;
long Seconds = mTimeLeftInMillis / 1000 % 60;
//
days.setText(String.format("%02d", Days));
hour.setText(String.format("%02d", Hours));
minute.setText(String.format("%02d", Minutes));
second.setText(String.format("%02d", Seconds));
}
@Override
public void onFinish() {
}
};
mCountDownTimer.start();
}
正如我之前所说的,当我设置时,
END_TIME="06.05.2021 05:56"
唯一的问题是当我从 firebase 数据库中获取相同的字符串时它不起作用。任何人都知道我非常感激的解决方案。
解决方案
推荐阅读
- c++ - 从线程执行成员方法时出现分段错误
- angular - 检测 @ViewChild() 中的值何时发生变化
- javascript - 在 Vue 的组件脚本中使用 slot-scoped 数据
- automated-tests - VSTS 发布管道运行后如何测试?
- neural-network - RNN 反向传播时间
- angular - Angular 2 Primeng 消息服务未显示消息
- java - PHP if-else 主体都在执行
- android - SQL 查询没有创建我的列?
- android - 使用 Glide V4 的相同 URL、不同图像的最佳性能
- reactjs - 反应:抽屉的内容不会在状态更改时呈现