增值并存储在Firebase中

时间:2019-01-03 13:54:50

标签: java android firebase firebase-realtime-database

我正在尝试为自动售货机模拟器构建一个应用程序,并将该值存储在Firebase中。

这是我的Firebase硬币面额和饮料数量数据:

This is my Firebase data for coin denomination and drink quantity

这是我的第一个活动: This is my first activity

这是我的第二项活动 This is my second activity

我想存储客户输入的每种面额的硬币(例如:如果客户输入20美分,则20美分的数量将在Firebase中加1,依此类推),但是我不知道该怎么做。饮料数量也会发生同样的问题(例如:如果数量=价格或数量>价格,则系统应分配饮料并将Firebase中的饮料数量减1)。

我了解逻辑,但是我不知道如何在android开发中实现它,因为我仍在学习和对此有所了解。

任何帮助将不胜感激。预先谢谢你。

这是我的DrinkActivity.java

public class DrinkActivity extends AppCompatActivity {

    Button terminateBtn;
    ImageButton tenCent, twentyCent, fiftyCent, oneRinggit, slugCoin1, slugCoin2;
    TextView amount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drink);

        // Receive data
        String name  = getIntent().getExtras().getString("name");
        String price = getIntent().getExtras().getString("price");
        String image_url = getIntent().getExtras().getString("img");

        // init view
        TextView tv_name = findViewById(R.id.aa_name);
        TextView tv_price = findViewById(R.id.aa_price);
        ImageView img = findViewById(R.id.aa_thumbnail);

        // setting values to each view
        tv_name.setText(name);
        tv_price.setText(String.valueOf(price));

        RequestOptions requestOptions = new RequestOptions().centerCrop().placeholder(R.drawable.loading_shape).error(R.drawable.loading_shape);

        // set image using Glide
        Glide.with(this).load(image_url).apply(requestOptions).into(img);

        //Amount
        amount = (TextView) findViewById(R.id.amountView);

        //Coin Button
        tenCent = (ImageButton) findViewById(R.id.cent10);
        twentyCent = (ImageButton) findViewById(R.id.cent20);
        fiftyCent = (ImageButton) findViewById(R.id.cent50);
        oneRinggit = (ImageButton) findViewById(R.id.rm1);
        slugCoin1 = (ImageButton) findViewById(R.id.unknown1);
        slugCoin2 = (ImageButton) findViewById(R.id.unknown2);

        terminateBtn = (Button) findViewById(R.id.terminateBtn);

        //Terminate button
        terminateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //When terminate the transaction, it should return the amount that already has
                //been inserted by the customer.
                Intent i = new Intent(DrinkActivity.this,Home.class);
                startActivity(i);
            }
        });

        //10 cent button
        tenCent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        amount.setText("RM 0.10");
                        playSound();
                    }
                }, 1000);
                amount.setText("Checking...");
            }
        });

        //20 cent button
        twentyCent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        amount.setText("RM 0.20");
                        playSound();
                    }
                }, 1000);
                amount.setText("Checking...");
            }
        });

        //50 cent button
        fiftyCent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        amount.setText("RM 0.50");
                        playSound();
                    }
                }, 1000);
                amount.setText("Checking...");
            }
        });

        //RM 1 button
        oneRinggit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        amount.setText("RM 1.00");
                        playSound();
                    }
                }, 1000);
                amount.setText("Checking...");
            }
        });

        //Slug coin 1 button
        slugCoin1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DrinkActivity.this, "Invalid Coin!" , Toast.LENGTH_SHORT).show();
                        amount.setText("RM 0.00");
                        slugCoinSound();
                    }
                }, 1000);
                amount.setText("Checking...");
            }
        });

        //Slug coin 2 button
        slugCoin2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DrinkActivity.this, "Invalid Coin!" , Toast.LENGTH_SHORT).show();
                        amount.setText("RM 0.00");
                        slugCoinSound();
                    }
                }, 1000);
                amount.setText("Checking...");
            }
        });

    }

    public void playSound() {
        MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.insert_coins);
        mediaPlayer.start();
    }

    public void slugCoinSound() {
        MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.change);
        mediaPlayer.start();
    }

}

1 个答案:

答案 0 :(得分:0)

您应该使用Firebase的runTransaction方法。这是您可以用于20美分硬币的示例代码。其他硬币的代码类似:

public void onClick(View view) {
DatabaseReference quantityRef = ref.child("yoururl/Coins/1/quantity");
quantityRef.runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        Integer currentValue = mutableData.getValue(Integer.class);
        if (currentValue == null) {
            mutableData.setValue(0);
        } else {
            mutableData.setValue(currentValue + 1);
        }

        return Transaction.success(mutableData);
    }

    @Override
    public void onComplete(DatabaseError databaseError, boolean committed, DataSnapshot dataSnapshot) {
       System.out.println("Value incremented");
    }
});
}

您也可以在addValueEventListener中实现它,但是这样做并发并不安全:

public void onClick(View view) {
    DatabaseReference ref = youdatabaseRef.child("Coins/1");
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int quantity = (int) dataSnapshot.child("quantity").getValue();
            ref.child("quantity").setValue(quantity++);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) { }
    });   
}

在代码ref中是对您的Firebase数据库的引用。您可以这样编码:

final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-data/fireblog");