+-
[Firebase Database Image我正在制作一个物联网应用,其中使用实时数据库显示传感器的值并将其保存到datbase类。
但是我不希望任何两个连续的值都相同。
在将其保存到数据库类之前,如何将以前的值与当前值进行比较。
confirm2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Get your custom_toast.xml layout
LayoutInflater inflater = getLayoutInflater();
final View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_layout_id));
//Initializing the text views
EditText editText = findViewById(R.id.link2);
final String link2 = editText.getText().toString();
EditText editText1 = findViewById(R.id.idvalue);
final String StringValue = editText1.getText().toString();
//Adding functionality to the text views
fire2 = new Firebase("https://iot.firebaseio.com/");
Firebase fireChild = fire2.child(link2+"/S1");
fireChild.setValue("7");
// Read from the database
myRef = FirebaseDatabase.getInstance().getReference();
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
if(StringValue.length()>0 && link2.length()>0) {
try {
status = dataSnapshot.child(link2 + "/Analog2").getValue().toString();}
catch (NullPointerException ignored){}
if(status==null){
TextView text4 = layout.findViewById(R.id.text4);
text4.setText(" Error: Wrong ID. ");
// Toast...
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 540);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
return;
}
else {
analogvalue = Integer.parseInt(status);
pin.setText(status);
String status2=status;
mDatabaseHelper.addData("Date: " + Date + " Value: "+status);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
// Failed to read value
// Log.w(TAG, "Failed to read value.", error.toException());
}
});
0
投票
投票
您可以在引用中存储两个值:
prevVal和currentVal,例如:
Object:
{
"value": currentVal,
"prev_value": prevVal
}
ref.setValue(value: „x”);
然后在addValueListener中时:
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
previousValue = snapshot.val().prevVal;
newValue = snapshot.val().value;
//then compare -> e.g. compareShomehow(previousVal, newVal)
//then save to db
//then update previousValue -> ref.setValue(prev_value:newValue);
}
0
投票
投票
经过大量的试验和错误,我找到了解决此问题的方法。首先,保存来自数据库的值,然后定义一个长度为2的数组,然后将数据库中的值保存到数组的1索引中,然后交换该数组的值,然后比较一个数组的值,例如:
status = dataSnapshot.child(link2 + "/Analog2").getValue().toString();}
val1 = [prev,curr]
val1[1] = status
val1[1],val1[0] = val1[0],val1[1]
if val1[0]!=val1[1]:
//Do something
这将在特定节点的值更改时起作用。