这是我的代码。
package com.example.manali.likeex;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity2 extends Activity implements View.OnClickListener {
Button senlike;
private DatabaseReference mdatabase;
private DatabaseReference user1;
int c;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button sendlike = (Button) findViewById(R.id.b1);
mdatabase= FirebaseDatabase.getInstance().getReference();
user1=mdatabase.child("Teacher");
sendlike.setOnClickListener(this);
}
//当用户点击firebase上的按钮计数器时会增加 public void onClick(查看视图) {
if(user1!=null)
{
c++;
}
//sets value to user1 node
user1.setValue(c);
}
public DatabaseReference getUser1()
{
return user1;
}
}
此代码仅在应用处于活动状态时增加计数器。当我们关闭应用程序时,再次重新启动它。计数器再次从1开始。因此我想维持这个计数器。
答案 0 :(得分:2)
您的教师表下可以有计数列:
App
---Teacher
------Count
然后使用它可以查询计数并将其放入变量中,这样您就可以增加值,然后更新firebase中的值:
public void onClick(View view) {
DatabaseReference ref = mdatabase.child("Teacher");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int count = (int) dataSnapshot.child("count").getValue();
ref.child("count").setValue(count++);
}
@Override
public void onCancelled(FirebaseError firebaseError) { }
});
}
答案 1 :(得分:2)
DatabaseReference upvotesRef = ref.child("server/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes");
upvotesRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Integer currentValue = mutableData.getValue(Integer.class);
if (currentValue == null) {
mutableData.setValue(1);
} else {
mutableData.setValue(currentValue + 1);
}
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean committed, DataSnapshot dataSnapshot) {
System.out.println("Transaction completed");
}
});