skip to Main Content

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.

2

Answers


  1. 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:

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

    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("your_node_path").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("your_node_path").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 🙂

    Login or Signup to reply.
  2. Assuming that you have layout that contains a button and looks similar to this:

    <?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="Long Press Button"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    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("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;
        }
    });
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search