开发者

String to Int with Android

I am new to Android programming, and I am making a number guessing game to get to know the basic Android code. In my program, I have an EditText (basically a TextField) and I was wondering how I would change whatever the user inputs into an int. So far I have tried Integer.parseInt(string), but it didn't work. Here is the code that I have right now:

EditText textfield = (EditText) findViewById(R.id.textfield);
String label = textfield.getText().toString();
int guess = Integer.parseInt(label);

When I run this program to debug on my phone, it all works fine until I press the button that I call this code with. When I press the button, the program closes and a popup comes that says

"The application Test (process com.android.test) has stopped unexpectedly. Please try again.开发者_JAVA技巧"

This happens every time I try to run the program. I have debugged, and I have isolated the problem to the line of code that parses the int. How do I make this work?


You're likely getting a NumberFormatException, but that isn't enough to help you except temporarily.

What you need to do is become familiar with some of the Android debugging facilities.

Start the phone emulator using the platform tools.

Open a command prompt and navigate to your android-sdk\platform-tools directory.

Run adb logcat to connect to the running emulator. In the emulator, run your program and cause the error to occur. You will get a stack trace in your command line window to help you isolate your problem.

Check out how to use LogCat on the dev site.


Whenever you get a crash, you need to print out the callstack. That shows you exactly what's wrong.

In this case, maybe you're not entering a number? Whenever you're parsing a string, be sure to put a try/catch around the Integer.parseInt, or else the user can crash your app by entering something that is not a number.

The only other options would be that R.id.textfield is not an EditText, or there is no R.id.textfield in this particular layout. If you had printed the stack trace, we'd know for sure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜