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

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

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

问题

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

package com.example.try6;

import androidx.appcompat.app.AppCompatActivity;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.try6.databinding.ActivityMainBinding;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;

public class MainActivity extends AppCompatActivity {
    // 其他代码...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 其他代码...
        initializeComponents();
    }

    private void initializeComponents() {
        // 其他代码...
        for (Button button : buttons) {
            button.setOnClickListener(view -> {
                if (button == binding.btnGasUp) {
                    setOnClick(1, "Gas");
                } else if (button == binding.btnGasDown) {
                    setOnClick(-1, "Gas");
                } else if (button == binding.btnYawRight) {
                    setOnClick(1, "Yaw");
                } else if (button == binding.btnYawLeft) {
                    setOnClick(-1, "Yaw");
                } else if (button == binding.btnRollRight) {
                    setOnClick(1, "Roll");
                } else if (button == binding.btnRollLeft) {
                    setOnClick(-1, "Roll");
                } else if (button == binding.btnPitchFront) {
                    setOnClick(1, "Pitch");
                } else if (button == binding.btnPitchBack) {
                    setOnClick(-1, "Pitch");
                }
            });

            button.setOnLongClickListener(view -> {
                if (button == binding.btnGasUp) {
                    setOnLongClick(number++, "Gas");
                } else if (button == binding.btnGasDown) {
                    setOnLongClick(number--, "Gas");
                } else if (button == binding.btnYawRight) {
                    setOnLongClick(number++, "Yaw");
                } else if (button == binding.btnYawLeft) {
                    setOnLongClick(number--, "Yaw");
                } else if (button == binding.btnRollRight) {
                    setOnLongClick(number++, "Roll");
                } else if (button == binding.btnRollLeft) {
                    setOnLongClick(number--, "Roll");
                } else if (button == binding.btnPitchFront) {
                    setOnLongClick(number++, "Pitch");
                } else if (button == binding.btnPitchBack) {
                    setOnLongClick(number--, "Pitch");
                }
                number = 0;
                return true;
            });
        }
    }

    private void setOnClick(int increment, String path) {
        // 其他代码...
    }

    private void setOnLongClick(int increment, String path) {
        // 其他代码...
    }
}

这是结果:
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 :

package com.example.try6;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.try6.databinding.ActivityMainBinding;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private DatabaseReference database;
private int number = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
initializeComponents();
}
private void initializeComponents() {
Button[] buttons = {
binding.btnGasUp, binding.btnGasDown,
binding.btnYawRight, binding.btnYawLeft,
binding.btnRollRight, binding.btnRollLeft,
binding.btnPitchFront, binding.btnPitchBack,
};
for (Button button : buttons) {
button.setOnClickListener(view -> {
if (button == binding.btnGasUp) {
setOnClick(1, "Gas");
} else if (button == binding.btnGasDown) {
setOnClick(-1, "Gas");
} else if (button == binding.btnYawRight) {
setOnClick(1, "Yaw");
} else if (button == binding.btnYawLeft) {
setOnClick(-1, "Yaw");
} else if (button == binding.btnRollRight) {
setOnClick(1, "Roll");
} else if (button == binding.btnRollLeft) {
setOnClick(-1, "Roll");
} else if (button == binding.btnPitchFront) {
setOnClick(1, "Pitch");
} else if (button == binding.btnPitchBack) {
setOnClick(-1, "Pitch");
}
});
button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (button == binding.btnGasUp) {
setOnLongClick(number++, "Gas");
} else if (button == binding.btnGasDown) {
setOnLongClick(number--,"Gas");
} else if (button == binding.btnYawRight) {
setOnLongClick(number++,"Yaw");
} else if (button == binding.btnYawLeft) {
setOnLongClick(number--,"Yaw");
} else if (button == binding.btnRollRight) {
setOnLongClick(number++,"Roll");
} else if (button == binding.btnRollLeft) {
setOnLongClick(number--,"Roll");
} else if (button == binding.btnPitchFront) {
setOnLongClick(number++, "Pitch");
} else if (button == binding.btnPitchBack) {
setOnLongClick(number--,"Pitch");
}
number = 0;
return true;
}
});
}
}
private void setOnClick(int increment, String path) {
database = FirebaseDatabase.getInstance().getReference("Control");
database.child(path).setValue(ServerValue.increment(increment)).addOnFailureListener(e -> {
CharSequence text = "The value was failed to add";
int toast = Toast.LENGTH_SHORT;
Toast.makeText(getApplicationContext(), text, toast).show();
});
}
private void setOnLongClick(int increment, String path){
database = FirebaseDatabase.getInstance().getReference("Control");
database.child(path).setValue(ServerValue.increment(increment)).addOnFailureListener(e -> {
CharSequence text = "The value was failed to add";
int toast = Toast.LENGTH_SHORT;
Toast.makeText(getApplicationContext(), text, toast).show();
});
}
}

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:

<Button
android:id="@+id/increaseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="增加"
/>

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

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

private DatabaseReference mDatabase;

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

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

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

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

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

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

increaseButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        increaseValue();
    }
});

increaseButton.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        startIncreasingValue();
        return true;
    }
});

实现增加值的方法:

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

private int value = 0;
private Handler handler = new Handler();
private Runnable increaseRunnable;

private void increaseValue() {
    value++;
    mDatabase.child("your_node_path").setValue(value);
}

private void startIncreasingValue() {
    increaseRunnable = new Runnable() {
        @Override
        public void run() {
            increaseValue();
            handler.postDelayed(this, 100); // 每100毫秒增加一次
        }
    };
    handler.post(increaseRunnable);
}

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

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

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_UP) {
        stopIncreasingValue();
    }
    return super.onTouchEvent(event);
}

private void stopIncreasingValue() {
    if (increaseRunnable != null) {
        handler.removeCallbacks(increaseRunnable);
        increaseRunnable = null;
    }
    value = 0;
    mDatabase.child("your_node_path").setValue(value);
}

请记得将“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:

&lt;Button
android:id=&quot;@+id/increaseButton&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;Increase&quot;
/&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:

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:

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:

Button increaseButton = findViewById(R.id.increaseButton);
increaseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
increaseValue();
}
});
increaseButton.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startIncreasingValue();
return true;
}
});

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:

private int value = 0;
private Handler handler = new Handler();
private Runnable increaseRunnable;
private void increaseValue() {
value++;
mDatabase.child(&quot;your_node_path&quot;).setValue(value);
}
private void startIncreasingValue() {
increaseRunnable = new Runnable() {
@Override
public void run() {
increaseValue();
handler.postDelayed(this, 100); // Increase every 100 milliseconds
}
};
handler.post(increaseRunnable);
}

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:

@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
stopIncreasingValue();
}
return super.onTouchEvent(event);
}
private void stopIncreasingValue() {
if (increaseRunnable != null) {
handler.removeCallbacks(increaseRunnable);
increaseRunnable = null;
}
value = 0;
mDatabase.child(&quot;your_node_path&quot;).setValue(value);
}

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

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

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/longPressButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="长按按钮"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

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

private Button longPressButton;
private Handler toastHandler;
private Runnable toastRunnable;
private boolean isButtonPressed;
private DatabaseReference valueRef;

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

longPressButton = findViewById(R.id.longPressButton);
toastHandler = new Handler();
isButtonPressed = false;
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
valueRef = db.child("value");

longPressButton.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isButtonPressed = true;
                incrementRepeatedly();
                return true;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                isButtonPressed = false;
                setValueToZero();
                return true;
        }
        return false;
    }
});

以下是相应的方法:

private void incrementRepeatedly() {
    toastRunnable = new Runnable() {
        @Override
        public void run() {
            if (isButtonPressed) {
                valueRef.setValue(ServerValue.increment(1));
                toastHandler.postDelayed(this, 500);
            }
        }
    };
    toastHandler.postDelayed(toastRunnable, 500);
}

private void setValueToZero() {
    valueRef.setValue(0);
}

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

英文:

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

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
tools:context=&quot;.MainActivity&quot;&gt;
&lt;Button
android:id=&quot;@+id/longPressButton&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;Long Press Button&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintLeft_toLeftOf=&quot;parent&quot;
app:layout_constraintRight_toRightOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;/&gt;
&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:

private Button longPressButton;
private Handler toastHandler;
private Runnable toastRunnable;
private boolean isButtonPressed;
private DatabaseReference valueRef;

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

longPressButton = findViewById(R.id.longPressButton);
toastHandler = new Handler();
isButtonPressed = false;
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
valueRef = db.child(&quot;value&quot;);
longPressButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isButtonPressed = true;
incrementRepeatedly();
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
isButtonPressed = false;
setValueToZero();
return true;
}
return false;
}
});

And here are the corresponding methods:

private void incrementRepeatedly() {
toastRunnable = new Runnable() {
@Override
public void run() {
if (isButtonPressed) {
valueRef.setValue(ServerValue.increment(1));
toastHandler.postDelayed(this, 500);
}
}
};
toastHandler.postDelayed(toastRunnable, 500);
}
private void setValueToZero() {
valueRef.setValue(0);
}

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:

确定