GoonyKnightMan
GoonyKnightMan

Reputation: 25

Android: How to Convert a number in a Buttons text to integer?

I'm making a simple dice rolling app as a way to learn some basics about Android Studio.

The method called onClick is shown below:

public void setSide(View v){
    Button b = (Button)v;
    sides = Integer.getInteger(b.getText().toString(),-1);
}

It seems to be passing -1 to sides no matter what, and all the buttons calling this method have only numbers in their strings (ex: "2", "20", "100", etc). Is there a way to fix this?

EDIT: I should probably explain that sides is local, and is used in another method, doRoll which is called the the Click of another button. This method sets the text of a textview to roll(sides), a method which returns a number from 1-sides if sides > 1, otherwise it returns -999. I have sides initialized to 20, and when I press the rollBtn before anything else, it works fine.

Upvotes: 0

Views: 2560

Answers (5)

Ferencz Andras
Ferencz Andras

Reputation: 41

sides = Integer.parseInt(button.getText().toString());

it works for me

Upvotes: 0

Ajinkya
Ajinkya

Reputation: 1039

check with only one condition :-

if(!TextUtils.isEmpty(b.getText().toString())){
    sides = Integer.getInteger(b.getText().toString());
} else {
    sides = -1;
}

Upvotes: 0

himanshu.tiwari
himanshu.tiwari

Reputation: 101

Try this and let me know:

public void setSide(View v){
Button b = (Button)v;
sides = Integer.parseInt(b.getText().toString());
}

Upvotes: 0

Sadeq Shajary
Sadeq Shajary

Reputation: 437

You can use this:

sides = Integer.parseInt(b.getText().toString());

Upvotes: 1

Vivek Mishra
Vivek Mishra

Reputation: 5705

Try like this

sides = Integer.parseInt(b.getText().toString());

Upvotes: 1

Related Questions