Dr. Danger
Dr. Danger

Reputation: 93

parseInt crashing android app

So I'm trying to make a calculator app (just to get a hang of android development), and I noticed with some testing that the parseInt conversion from "String tack1" is causing the app to crash. Can someone tell me why? I can't seem to figure it out and I've been searching the internet for quite a while now. (hehe I'm a noob so please go easy) In the code below, I've modified a couple lines to make it seem obvious what it's supposed to print however it still crashes. Here's the code:


equals.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            oC = 1; //operator checker is on 1 (for plus)
            switch(oC){ //check for operator clicked
                case 0: break;
                case 1:
                   tack1 = "1"; //INSERTED THIS TO MAKE OUTPUT OBVIOUS
                   tack1 = tack1.trim(); tack2 = tack2.trim(); //INSERTED BEFORE TO DEAL WITH WHITESPACE
                   numOne = Integer.parseInt(tack1); //CRASHES HERE
                   answer.setText(numOne);
                   modeChecker = 0; oC = 0;break;

NOTES ON PROGRAM(some of comments repeated and other stuff as well):

The tack1 = "1"; is to make output obvious

The tack1.trim() is to deal with whitespace

Yes whatever is in tack is a number and an integer (not even a negative integer)

Yes numOne is an integer and is defined wayy above (not in code listed here)

Sorry the indents are all messed up(after case 1) because of the comments I added

This is a section of my onClick method, so closing brackets aren't included in here.

Can someone please help me? THANKYOU :D

Upvotes: 3

Views: 1619

Answers (1)

Rich
Rich

Reputation: 36806

I'd be willing to bet it's actually crashing on the following line AFTER the call to parseInt.

You're calling setText(int) on your TextView. When you pass an int to this method, that int is a pointer to a string resource...you're probably expecting an auto-conversion to a string. Since you are passing it an int that is generated in your application, it's extremely unlikely that this int also points to a string resource in your res/values/strings.xml file. What you really want to do is change numOne to a string first, which you can do inline:

Change

answer.setText(numOne);

to

answer.setText(String.valueOf(numOne));

and you're good to go.

Upvotes: 4

Related Questions