如何在Android Studio中通过连续按按钮来增加Firebase中的值。

huangapple go评论108阅读模式
英文:

How to Increase Value in Firebase by Pressing Button Continuously in Android Studio

问题

我是Android Studio的新手,现在我想创建一些按钮,每当我点击按钮时,就可以增加我的Firebase实时数据库的值。但是,我希望每当我长按按钮时,该值保持增加,而当我松开按钮时,该值返回零。我尝试过编写代码,下面是我的MainActivity代码:

  1. package com.example.try6;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.content.pm.ActivityInfo;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.widget.Button;
  7. import android.widget.Toast;
  8. import com.example.try6.databinding.ActivityMainBinding;
  9. import com.google.firebase.database.DatabaseReference;
  10. import com.google.firebase.database.FirebaseDatabase;
  11. import com.google.firebase.database.ServerValue;
  12. public class MainActivity extends AppCompatActivity {
  13. // 其他代码...
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. // 其他代码...
  17. initializeComponents();
  18. }
  19. private void initializeComponents() {
  20. // 其他代码...
  21. for (Button button : buttons) {
  22. button.setOnClickListener(view -> {
  23. if (button == binding.btnGasUp) {
  24. setOnClick(1, "Gas");
  25. } else if (button == binding.btnGasDown) {
  26. setOnClick(-1, "Gas");
  27. } else if (button == binding.btnYawRight) {
  28. setOnClick(1, "Yaw");
  29. } else if (button == binding.btnYawLeft) {
  30. setOnClick(-1, "Yaw");
  31. } else if (button == binding.btnRollRight) {
  32. setOnClick(1, "Roll");
  33. } else if (button == binding.btnRollLeft) {
  34. setOnClick(-1, "Roll");
  35. } else if (button == binding.btnPitchFront) {
  36. setOnClick(1, "Pitch");
  37. } else if (button == binding.btnPitchBack) {
  38. setOnClick(-1, "Pitch");
  39. }
  40. });
  41. button.setOnLongClickListener(view -> {
  42. if (button == binding.btnGasUp) {
  43. setOnLongClick(number++, "Gas");
  44. } else if (button == binding.btnGasDown) {
  45. setOnLongClick(number--, "Gas");
  46. } else if (button == binding.btnYawRight) {
  47. setOnLongClick(number++, "Yaw");
  48. } else if (button == binding.btnYawLeft) {
  49. setOnLongClick(number--, "Yaw");
  50. } else if (button == binding.btnRollRight) {
  51. setOnLongClick(number++, "Roll");
  52. } else if (button == binding.btnRollLeft) {
  53. setOnLongClick(number--, "Roll");
  54. } else if (button == binding.btnPitchFront) {
  55. setOnLongClick(number++, "Pitch");
  56. } else if (button == binding.btnPitchBack) {
  57. setOnLongClick(number--, "Pitch");
  58. }
  59. number = 0;
  60. return true;
  61. });
  62. }
  63. }
  64. private void setOnClick(int increment, String path) {
  65. // 其他代码...
  66. }
  67. private void setOnLongClick(int increment, String path) {
  68. // 其他代码...
  69. }
  70. }

这是结果:
Firebase实时数据库上的结果

它可以处理setOnClickListener()事件,尽管值没有返回零(只有在我单击按钮时值才会增加),但setOnLongClickListener()事件根本不起作用。有什么建议吗?或者我有些错误吗?对于我的糟糕英语表示抱歉。

英文:

I am new to using Android Studio, and now I want to create some buttons which can increase the value of my Firebase Realtime Database whenever I click the button. However, I want to make the value keep increasing whenever I long click the button, and the value returns to zero when I release the button. I have tried to code and here's my MainActivity code :

  1. package com.example.try6;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.content.pm.ActivityInfo;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.widget.Button;
  7. import android.widget.Toast;
  8. import com.example.try6.databinding.ActivityMainBinding;
  9. import com.google.firebase.database.DatabaseReference;
  10. import com.google.firebase.database.FirebaseDatabase;
  11. import com.google.firebase.database.ServerValue;
  12. public class MainActivity extends AppCompatActivity {
  13. private ActivityMainBinding binding;
  14. private DatabaseReference database;
  15. private int number = 0;
  16. @Override
  17. protected void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. binding = ActivityMainBinding.inflate(getLayoutInflater());
  20. View view = binding.getRoot();
  21. setContentView(view);
  22. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
  23. initializeComponents();
  24. }
  25. private void initializeComponents() {
  26. Button[] buttons = {
  27. binding.btnGasUp, binding.btnGasDown,
  28. binding.btnYawRight, binding.btnYawLeft,
  29. binding.btnRollRight, binding.btnRollLeft,
  30. binding.btnPitchFront, binding.btnPitchBack,
  31. };
  32. for (Button button : buttons) {
  33. button.setOnClickListener(view -> {
  34. if (button == binding.btnGasUp) {
  35. setOnClick(1, "Gas");
  36. } else if (button == binding.btnGasDown) {
  37. setOnClick(-1, "Gas");
  38. } else if (button == binding.btnYawRight) {
  39. setOnClick(1, "Yaw");
  40. } else if (button == binding.btnYawLeft) {
  41. setOnClick(-1, "Yaw");
  42. } else if (button == binding.btnRollRight) {
  43. setOnClick(1, "Roll");
  44. } else if (button == binding.btnRollLeft) {
  45. setOnClick(-1, "Roll");
  46. } else if (button == binding.btnPitchFront) {
  47. setOnClick(1, "Pitch");
  48. } else if (button == binding.btnPitchBack) {
  49. setOnClick(-1, "Pitch");
  50. }
  51. });
  52. button.setOnLongClickListener(new View.OnLongClickListener() {
  53. @Override
  54. public boolean onLongClick(View view) {
  55. if (button == binding.btnGasUp) {
  56. setOnLongClick(number++, "Gas");
  57. } else if (button == binding.btnGasDown) {
  58. setOnLongClick(number--,"Gas");
  59. } else if (button == binding.btnYawRight) {
  60. setOnLongClick(number++,"Yaw");
  61. } else if (button == binding.btnYawLeft) {
  62. setOnLongClick(number--,"Yaw");
  63. } else if (button == binding.btnRollRight) {
  64. setOnLongClick(number++,"Roll");
  65. } else if (button == binding.btnRollLeft) {
  66. setOnLongClick(number--,"Roll");
  67. } else if (button == binding.btnPitchFront) {
  68. setOnLongClick(number++, "Pitch");
  69. } else if (button == binding.btnPitchBack) {
  70. setOnLongClick(number--,"Pitch");
  71. }
  72. number = 0;
  73. return true;
  74. }
  75. });
  76. }
  77. }
  78. private void setOnClick(int increment, String path) {
  79. database = FirebaseDatabase.getInstance().getReference("Control");
  80. database.child(path).setValue(ServerValue.increment(increment)).addOnFailureListener(e -> {
  81. CharSequence text = "The value was failed to add";
  82. int toast = Toast.LENGTH_SHORT;
  83. Toast.makeText(getApplicationContext(), text, toast).show();
  84. });
  85. }
  86. private void setOnLongClick(int increment, String path){
  87. database = FirebaseDatabase.getInstance().getReference("Control");
  88. database.child(path).setValue(ServerValue.increment(increment)).addOnFailureListener(e -> {
  89. CharSequence text = "The value was failed to add";
  90. int toast = Toast.LENGTH_SHORT;
  91. Toast.makeText(getApplicationContext(), text, toast).show();
  92. });
  93. }
  94. }

And this is the result :
The Result on Firebase Realtime Database

It works for setOnClickListener() event even though the value did not return to zero (The value increase whenever i click the button only) but the setOnLongClickListener() event did not work at all.
Any suggestions what should i do? Or am i do some mistakes?
Sorry for my poor English.

答案1

得分: 2

设计您的布局:

打开您的布局XML文件(例如,activity_main.xml)并添加一个按钮元素。您可以根据需要自定义其外观。
按钮的示例XML:

  1. <Button
  2. android:id="@+id/increaseButton"
  3. android:layout_width="wrap_content"
  4. android:layout_height="wrap_content"
  5. android:text="增加"
  6. />

检索到Firebase实时数据库的引用:

在您的活动或片段中,声明一个Firebase实时数据库引用的变量。
示例代码:

  1. private DatabaseReference mDatabase;

初始化Firebase实时数据库引用:

在您的活动的onCreate()方法或片段的onViewCreated()方法中,初始化数据库引用。
示例代码:

  1. mDatabase = FirebaseDatabase.getInstance().getReference();

为按钮设置单击和长按监听器:

在您的活动或片段中,通过其ID查找按钮并为其设置单击监听器和长按监听器。
示例代码:

  1. Button increaseButton = findViewById(R.id.increaseButton);
  2. increaseButton.setOnClickListener(new View.OnClickListener() {
  3. @Override
  4. public void onClick(View v) {
  5. increaseValue();
  6. }
  7. });
  8. increaseButton.setOnLongClickListener(new View.OnLongClickListener() {
  9. @Override
  10. public boolean onLongClick(View v) {
  11. startIncreasingValue();
  12. return true;
  13. }
  14. });

实现增加值的方法:

在您的活动或片段中创建两个方法,increaseValue()和startIncreasingValue(),用于处理增加值的逻辑并在Firebase中更新它。
示例代码:

  1. private int value = 0;
  2. private Handler handler = new Handler();
  3. private Runnable increaseRunnable;
  4. private void increaseValue() {
  5. value++;
  6. mDatabase.child("your_node_path").setValue(value);
  7. }
  8. private void startIncreasingValue() {
  9. increaseRunnable = new Runnable() {
  10. @Override
  11. public void run() {
  12. increaseValue();
  13. handler.postDelayed(this, 100); // 每100毫秒增加一次
  14. }
  15. };
  16. handler.post(increaseRunnable);
  17. }

当按钮释放时停止增加值:

覆盖您的活动或片段中的onTouchEvent()方法,并在按钮释放时停止增加机制。
示例代码:

  1. @Override
  2. public boolean onTouchEvent(MotionEvent event) {
  3. if (event.getAction() == MotionEvent.ACTION_UP) {
  4. stopIncreasingValue();
  5. }
  6. return super.onTouchEvent(event);
  7. }
  8. private void stopIncreasingValue() {
  9. if (increaseRunnable != null) {
  10. handler.removeCallbacks(increaseRunnable);
  11. increaseRunnable = null;
  12. }
  13. value = 0;
  14. mDatabase.child("your_node_path").setValue(value);
  15. }

请记得将“your_node_path”替换为Firebase实时数据库中所需节点的实际路径。

这些步骤将允许您在Android应用中创建一个按钮,当点击时会增加Firebase实时数据库中的值,并在长按时保持增加。当按钮释放时,值将重置为零。

如果您有任何问题,请随时告诉我 如何在Android Studio中通过连续按按钮来增加Firebase中的值。

英文:

Design your layout:

Open your layout XML file (e.g., activity_main.xml) and add a button element. You can customize its appearance as desired.
Example XML for the button:

  1. &lt;Button
  2. android:id=&quot;@+id/increaseButton&quot;
  3. android:layout_width=&quot;wrap_content&quot;
  4. android:layout_height=&quot;wrap_content&quot;
  5. android:text=&quot;Increase&quot;
  6. /&gt;

Retrieve a reference to your Firebase Realtime Database:

In your activity or fragment, declare a variable for the Firebase Realtime Database reference.
Example code:

  1. private DatabaseReference mDatabase;

Initialize the Firebase Realtime Database reference:

Inside your activity's onCreate() method or fragment's onViewCreated() method, initialize the database reference.
Example code:

  1. mDatabase = FirebaseDatabase.getInstance().getReference();

Set click and long-click listeners for the button:

In your activity or fragment, find the button by its ID and set both a click listener and a long-click listener on it.
Example code:

  1. Button increaseButton = findViewById(R.id.increaseButton);
  2. increaseButton.setOnClickListener(new View.OnClickListener() {
  3. @Override
  4. public void onClick(View v) {
  5. increaseValue();
  6. }
  7. });
  8. increaseButton.setOnLongClickListener(new View.OnLongClickListener() {
  9. @Override
  10. public boolean onLongClick(View v) {
  11. startIncreasingValue();
  12. return true;
  13. }
  14. });

Implement the methods for increasing the value:

Create two methods, increaseValue() and startIncreasingValue(), in your activity or fragment to handle the logic of increasing the value and updating it in Firebase.
Example code:

  1. private int value = 0;
  2. private Handler handler = new Handler();
  3. private Runnable increaseRunnable;
  4. private void increaseValue() {
  5. value++;
  6. mDatabase.child(&quot;your_node_path&quot;).setValue(value);
  7. }
  8. private void startIncreasingValue() {
  9. increaseRunnable = new Runnable() {
  10. @Override
  11. public void run() {
  12. increaseValue();
  13. handler.postDelayed(this, 100); // Increase every 100 milliseconds
  14. }
  15. };
  16. handler.post(increaseRunnable);
  17. }

Stop increasing the value when the button is released:

Override the onTouchEvent() method in your activity or fragment and stop the increasing mechanism when the button is released.
Example code:

  1. @Override
  2. public boolean onTouchEvent(MotionEvent event) {
  3. if (event.getAction() == MotionEvent.ACTION_UP) {
  4. stopIncreasingValue();
  5. }
  6. return super.onTouchEvent(event);
  7. }
  8. private void stopIncreasingValue() {
  9. if (increaseRunnable != null) {
  10. handler.removeCallbacks(increaseRunnable);
  11. increaseRunnable = null;
  12. }
  13. value = 0;
  14. mDatabase.child(&quot;your_node_path&quot;).setValue(value);
  15. }

Remember to replace "your_node_path" with the actual path to your desired node in the Firebase Realtime Database.

These steps will allow you to create a button in your Android app that increases the value in your Firebase Realtime Database when clicked and keeps increasing when long-pressed. The value will reset to zero when the button is released.

Please let me know if you have any questions 如何在Android Studio中通过连续按按钮来增加Firebase中的值。

答案2

得分: 0

假设您有一个包含按钮并且看起来类似于以下内容的布局:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. tools:context=".MainActivity">
  8. <Button
  9. android:id="@+id/longPressButton"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:text="长按按钮"
  13. app:layout_constraintBottom_toBottomOf="parent"
  14. app:layout_constraintLeft_toLeftOf="parent"
  15. app:layout_constraintRight_toRightOf="parent"
  16. app:layout_constraintTop_toTopOf="parent"/>
  17. </androidx.constraintlayout.widget.ConstraintLayout>

为了实现这样的功能:在按钮按下时每500毫秒增加一个值,当按钮释放时将该值设置为零。请在您的活动内定义以下五个全局变量:

  1. private Button longPressButton;
  2. private Handler toastHandler;
  3. private Runnable toastRunnable;
  4. private boolean isButtonPressed;
  5. private DatabaseReference valueRef;

然后在 onCreate() 方法内添加以下代码行:

  1. longPressButton = findViewById(R.id.longPressButton);
  2. toastHandler = new Handler();
  3. isButtonPressed = false;
  4. DatabaseReference db = FirebaseDatabase.getInstance().getReference();
  5. valueRef = db.child("value");
  6. longPressButton.setOnTouchListener(new View.OnTouchListener() {
  7. @Override
  8. public boolean onTouch(View v, MotionEvent event) {
  9. switch (event.getAction()) {
  10. case MotionEvent.ACTION_DOWN:
  11. isButtonPressed = true;
  12. incrementRepeatedly();
  13. return true;
  14. case MotionEvent.ACTION_UP:
  15. case MotionEvent.ACTION_CANCEL:
  16. isButtonPressed = false;
  17. setValueToZero();
  18. return true;
  19. }
  20. return false;
  21. }
  22. });

以下是相应的方法:

  1. private void incrementRepeatedly() {
  2. toastRunnable = new Runnable() {
  3. @Override
  4. public void run() {
  5. if (isButtonPressed) {
  6. valueRef.setValue(ServerValue.increment(1));
  7. toastHandler.postDelayed(this, 500);
  8. }
  9. }
  10. };
  11. toastHandler.postDelayed(toastRunnable, 500);
  12. }
  13. private void setValueToZero() {
  14. valueRef.setValue(0);
  15. }

要使其在您的项目中工作,您需要在数据库中设置自己的引用。

英文:

Assuming that you have layout that contains a button and looks similar to this:

  1. &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
  2. &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
  3. xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
  4. xmlns:tools=&quot;http://schemas.android.com/tools&quot;
  5. android:layout_width=&quot;match_parent&quot;
  6. android:layout_height=&quot;match_parent&quot;
  7. tools:context=&quot;.MainActivity&quot;&gt;
  8. &lt;Button
  9. android:id=&quot;@+id/longPressButton&quot;
  10. android:layout_width=&quot;wrap_content&quot;
  11. android:layout_height=&quot;wrap_content&quot;
  12. android:text=&quot;Long Press Button&quot;
  13. app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
  14. app:layout_constraintLeft_toLeftOf=&quot;parent&quot;
  15. app:layout_constraintRight_toRightOf=&quot;parent&quot;
  16. app:layout_constraintTop_toTopOf=&quot;parent&quot;/&gt;
  17. &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

To achieve a functionality in which you increment a value every 500 milliseconds while the button is pressed and when the button is released, to set the value to zero, then please define inside your activity five global variables:

  1. private Button longPressButton;
  2. private Handler toastHandler;
  3. private Runnable toastRunnable;
  4. private boolean isButtonPressed;
  5. private DatabaseReference valueRef;

And inside onCreate(), add the following lines of code:

  1. longPressButton = findViewById(R.id.longPressButton);
  2. toastHandler = new Handler();
  3. isButtonPressed = false;
  4. DatabaseReference db = FirebaseDatabase.getInstance().getReference();
  5. valueRef = db.child(&quot;value&quot;);
  6. longPressButton.setOnTouchListener(new View.OnTouchListener() {
  7. @Override
  8. public boolean onTouch(View v, MotionEvent event) {
  9. switch (event.getAction()) {
  10. case MotionEvent.ACTION_DOWN:
  11. isButtonPressed = true;
  12. incrementRepeatedly();
  13. return true;
  14. case MotionEvent.ACTION_UP:
  15. case MotionEvent.ACTION_CANCEL:
  16. isButtonPressed = false;
  17. setValueToZero();
  18. return true;
  19. }
  20. return false;
  21. }
  22. });

And here are the corresponding methods:

  1. private void incrementRepeatedly() {
  2. toastRunnable = new Runnable() {
  3. @Override
  4. public void run() {
  5. if (isButtonPressed) {
  6. valueRef.setValue(ServerValue.increment(1));
  7. toastHandler.postDelayed(this, 500);
  8. }
  9. }
  10. };
  11. toastHandler.postDelayed(toastRunnable, 500);
  12. }
  13. private void setValueToZero() {
  14. valueRef.setValue(0);
  15. }

To make it work in your project, you have to set your own references in the database.

huangapple
  • 本文由 发表于 2023年6月15日 01:21:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476101.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定