Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

java - Convert number in textview to int

So, I am messing around with java/android programming and right now I am trying to make a really basic calculator. I am hung up on this issue though. This is the code I have right now for getting the number thats in the textview and making it an int

CharSequence value1 = getText(R.id.textView);
int num1 =  Integer.parseInt(value1.toString());

And from what I can tell it is the second line that is causing the error, but im not sure why it is doing that. It is compiling fine, but when it tries to run this part of the program it crashes my app. And the only thing thats in the textview is numbers

Any advice?

I can also provide more of my code if necessary

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can read on the usage of TextView.

How to declare it:

TextView tv;

Initialize it:

tv = (TextView) findViewById(R.id.textView);

or:

tv = new TextView(MyActivity.this);

or, if you are inflating a layout,

tv = (TextView) inflatedView.findViewById(R.id.textView);

To set a string to tv, use tv.setText(some_string) or tv.setText("this_string"). If you need to set an integer value, use tv.setText("" + 5) as setText() is an overloaded method that can handle string and int arguments.

To get a value from tv use tv.getText().

Always check if the parser can handle the possible values that textView.getText().toString() can supply. A NumberFormatException is thrown if you try to parse an empty string(""). Or, if you try to parse ..

String tvValue = tv.getText().toString();

if (!tvValue.equals("") && !tvValue.equals(......)) {
    int num1 = Integer.parseInt(tvValue);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...