android - 不幸的是Android应用程序已停止

标签 android

我正在做一个简单的程序,用于添加从 EditText 输入的两个数字。 但是,当用户单击“单击以添加”按钮,将字段留空时,程序退出并显示“不幸的是,程序已停止。”

代码如下:

public class MainActivity extends Activity {

long a, b, sum;
Button add, clr;
EditText e1, e2, res;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    add = (Button) findViewById(R.id.bAdd);
    add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) throws NumberFormatException {
            // TODO Auto-generated method stub

                e1 = (EditText) findViewById(R.id.tv1);         
                String str1 = e1.getText().toString();

                e2 = (EditText) findViewById(R.id.tv2);
                String str2 = e2.getText().toString();

                try{
                    a = Integer.parseInt(str1);
                    b = Integer.parseInt(str2);
                }catch(NumberFormatException e){
                    res.setText("Please enter valid entries");
                }

                sum = a + b;    

                res = (EditText) findViewById(R.id.result);
                res.setText("Your sum is " + sum);
        }
    });

    clr = (Button) findViewById(R.id.bClr);
    clr.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) throws NumberFormatException {
            // TODO Auto-generated method stub
            e1.setText("");
            e2.setText("");
            res.setText("");
        }
    });
}

}

我希望应用对空白的 EditText 条目响应“请输入有效条目”。

最佳答案

你的线路:

res = (EditText) findViewById(R.id.result);

必须移动以便在使用 res.setText 之前初始化 res 变量。它没有在你的 catch 语句中初始化。 将其移动到如下所示的位置。您可以在执行其他操作时初始化它 findViewById

e1 = (EditText) findViewById(R.id.tv1); 
e2 = (EditText) findViewById(R.id.tv2);
res = (EditText) findViewById(R.id.result);

关于android - 不幸的是Android应用程序已停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13856461/

相关文章:

android - 是否必须删除 Intent extra?

android - 对自定义小部件实现单选/复选框逻辑

android - Play 结算库缺少 developerPayload

java - 如何将句子中的单词存储在java命令提示符中的单独字符串中

删除指纹时 Android key 失效

java - 在 Android 中将对象添加到 ArrayList 时出现 NullPointerException

android - 在 RadioGroup 上调用 clearCheck() 后调用 RadioGroup 的 setOnCheckedChangeListener 两次

android - Xcode 打不开 "Required content for Platform Android is missing"

从 C++ 库项目引用共享库的 Android native 项目

Android:ScaleType ="fitXY"不适用于所有图像