stvo62
stvo62

Reputation: 21

Button needed to be pressed twice for any action in Java

I'm having a little problem with buttons in Android Studio. To get any of my buttons to work, they all need to be pressed twice. I only want one press to have the action happen.

The one example below takes a value from an edit text box and inserts it into a database, then shows a toast. Just like I mentioned In need to press the button twice to enter the data and show the toast.

public void AddDataHR(View view) {
    buttonAddHR.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isInserted = mydb.insertDataHR(editHR.getText().toString());//Takes value from edittext and send it to insertDataHR within DatabaseHelper
                    if (isInserted == true)
                        Toast.makeText(HeartRate.this, "Data Inserted", Toast.LENGTH_LONG).show();//confirms data was inserted
                    else
                        Toast.makeText(HeartRate.this, "Data Not Inserted", Toast.LENGTH_LONG).show();//error message
                }
            }
    );
}

Here is the xml for the button to activate the above code.

<Button
    android:id="@+id/buttonAddHR"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView4"
    android:layout_alignStart="@+id/textView4"
    android:layout_centerVertical="true"
    android:layout_marginLeft="13dp"
    android:layout_marginStart="13dp"
    android:onClick="AddDataHR"
    android:text="Add Data Manually" />

I'm fairly new to Android Studio and Java, so I can get things to work, but not properly. Any help would be greatly appreciated! Thank you.

Upvotes: 2

Views: 568

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

Issue :

First click : set anonymous listener on button using buttonAddHR.setOnClickListener

Second click : trigger the anonymous click listener

Just use

public void AddDataHR(View view) {
        boolean isInserted = mydb.insertDataHR(editHR.getText().toString());//Takes value from edittext and send it to insertDataHR within DatabaseHelper
        if (isInserted)
            Toast.makeText(HeartRate.this, "Data Inserted", Toast.LENGTH_LONG).show();//confirms data was inserted
        else
            Toast.makeText(HeartRate.this, "Data Not Inserted", Toast.LENGTH_LONG).show();//error message
}

Upvotes: 5

Related Questions