我制作了一个关于我所在城市当前金属价格的应用程序。我每隔几个小时就会更新金属费率。我有一个TextView,当且仅当新的Rate更新时(由我在控制台中)更新当前时间和日期。现在,问题是,即使应用程序处于脱机状态,我的TextView也会使用当前时间进行更新。意味着addValueEventListener处于活动状态并正在侦听。如果应用程序处于脱机状态,或者除非我手动更新,否则我不希望更新TextView。这是我的代码 -
mFirebaseDatabaseInstance.getReference("metals").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String ratesteel= dataSnapshot.getValue(String.class);
tvsteelrate.setText(ratesteel);
//getting notification of updated price
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(MainActivity.this)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("ST")
.setContentText("Updated")
.setAutoCancel(true);
.setSound(defaultSoundUri);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(count, notificationBuilder.build());
count++;
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c);
mydate.setText(formattedDate);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
}
如果应用离线或未更新,如何禁用TextView更新?
答案 0 :(得分:0)
如果您希望代码仅在调用时执行,请使用.addListenerForSingleValueEvent()
mFirebaseDatabaseInstance.getReference("metals").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// do your stuff here
}
@Override
public void onCancelled(DatabaseError databaseError) {
// handle error
}
});