如何检索和更新firebase中的特定值

时间:2017-04-07 09:48:53

标签: android firebase firebase-realtime-database

我一直在研究用户因完成挑战而获得奖励的应用程序。目前,用户每完成一次挑战获得10分。但是我需要做到这一点,以便每次用户完成挑战时用户分数都会更新,换句话说,这些分数将从数据库中提取并添加额外的分数。 (需要在userID与userID匹配的位置更新点数)

如果有任何建议,我怎么能解决这个问题。

public void stopActivity(){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Confirm");
    builder.setMessage("Are you sure you want to stop?");

    builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {

            // Get the activity results
            String speedText = speedTxt.getText().toString();
            String distanceText = distanceTxt.getText().toString();
            String timeText = timeTxt.getText().toString();

            Toast.makeText(getApplicationContext(),"Your result is: " + "\n" + speedText + "\n" + distanceText + "\n" + timeText, Toast.LENGTH_LONG).show();

            //if the result is better
            if(Double.parseDouble(speed_challege) == Double.parseDouble(speedText) || Double.parseDouble(speed_challege) < Double.parseDouble(speedText) ){
                Toast.makeText(getApplicationContext(),"You completed the challenge", Toast.LENGTH_LONG).show();

                //award points if challenge is completed
                final DatabaseReference newResult = leaderBoard.push();
                String username = mCurrentUser.getEmail();

                //trim email leaving just username
                int index = username.indexOf('@');
                username = username.substring(0,index);

                newResult.child("UserName").setValue(username);
                newResult.child("uID").setValue(mAuth.getCurrentUser().getUid());
                newResult.child("Score").setValue(score);
            }

            //if result is worse
            else{
                Toast.makeText(getApplicationContext(),"Hard Luck Try again", Toast.LENGTH_LONG).show();
            }

            dialog.dismiss();
        }
    });

enter image description here

1 个答案:

答案 0 :(得分:0)

您是否添加了具有** firebase context **的java类?

 com.firebase.client.Firebase;
 import com.google.firebase.FirebaseApp;
 import com.google.firebase.database.FirebaseDatabase;


public class `FirebaseContext` extends android.app.Application {
@Override
public void onCreate() {
    super.onCreate();
    enter code hereFirebase.setAndroidContext(this);
    if(!FirebaseApp.getApps(this).isEmpty()){
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    }
  }
}