应用程序不断崩溃

时间:2012-03-10 18:57:52

标签: java android android-emulator

嘿,我是编程的新手,所以我想我会做一个简单的c到f转换器,但它在我打开之前一直在模拟器上崩溃可以让任何人看到原因吗?我知道这些代码在概率上都是错误的,但它是我能想到的唯一方法

package com.jamie.convert;

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

public class ConvertorActivity extends Activity implements OnClickListener {

    TextView textout1;
    EditText textIn1;
    Button convert;
    int x=Integer.parseInt(textIn1.getText().toString());
    double fahrenheit = 1.8*x;



    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        convert = (Button) findViewById(R.id.convert);
        textIn1=(EditText) findViewById(R.id.input);
        textout1=(TextView) findViewById(R.id.output);
        convert.setOnClickListener((android.view.View.OnClickListener)this);

    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.convert) {
            textout1.setText(""+fahrenheit);
        }


    }
}

3 个答案:

答案 0 :(得分:0)

尝试String.valueOf(fahrenheit); 而不是你的onClick中的华氏度

也移动你的

int x=Integer.parseInt(textIn1.getText().toString());

到onclick方法

答案 1 :(得分:0)

int x=Integer.parseInt(textIn1.getText().toString());

上述行将在Activity启动后立即执行。此时,textIn1将为null

这条线也不应该这样......

double fahrenheit = 1.8*x;

用......替换这些行

int x;
double fahrenheit;

...然后将onClick()方法更改为...

@Override
public void onClick(View v) {
    if(v.getId() == R.id.convert) {
        x = Integer.parseInt(textIn1.getText().toString());
        fahrenheit = x * 1.8 + 32
        textout1.setText(String.valueOf(fahrenheit));
    }
}

答案 2 :(得分:0)

使用此代码代替此代码,您将获得答案

TextView textout1;
EditText textIn1;
Button convert;
static int x;
//int x=Integer.parseInt(textIn1.getText().toString());
//double fahrenheit = 1.8*x;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    convert = (Button) findViewById(R.id.button1);
    textIn1=(EditText) findViewById(R.id.editText1);
    textout1=(TextView) findViewById(R.id.textView1);
    convert.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            x=Integer.parseInt(textIn1.getText().toString());
            double fahrenheit = 1.8*x;
            textout1.setText(""+fahrenheit);
        }
    });

}

由于您的int x不会从edittext获取任何值,因此会出现这种情况。