开发者

String to Integer not working

开发者 https://www.devze.com 2023-01-05 18:21 出处:网络
Humm... I can do this easily 开发者_运维知识库in Java (and all other languages) but, it doesn\'t seem to work in Android.

Humm... I can do this easily 开发者_运维知识库in Java (and all other languages) but, it doesn't seem to work in Android.

I simply want to get an integer number input from the user, press a button and do some simple math on it, then display it.

I'm using a TextEdit (also tried a TextView) and have tried many different approaches but, none work. The code itself has no errors and I can do the math and display it if using constants.

The problem is in either parsing it to an integer (though, the code-line seems ok, even though it's a tad different than what I use in pure java.

Any help is welcome - I'm sure it's simple and I read many related posts for this, including the Android Dev site - but...

Here's the short complete code:

package com.bt.strint;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class string_integer extends Activity {
    /** Called when the activity is first created. */   
    int aa = 3;
    int y=33;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

      final TextView input = (TextView) findViewById(R.id.EditText01);           
      final Button btn = (Button) findViewById(R.id.Button01);
      final TextView showMe = (TextView) findViewById(R.id.TextView01); 

      btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            //showMe.setText("meow");       //ok            
            //showMe.setText(String.valueOf(y * 7)); // ok
            y = Integer.parseInt((String) input.getText());
            showMe.setText(String.valueOf(y));
        }
      });       
    }
}


You want to use input.getText().toString(), instead of (String) input.getText(); you can't just cast a CharSequence to String.

0

精彩评论

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