Java代码中的应用程序错误,在Android应用程序中使用复选框保存输入和计算的多个数据

Java代码中的应用程序错误,在Android应用程序中使用复选框保存输入和计算的多个数据,java,android,checkbox,android-sdcard,buttonclick,Java,Android,Checkbox,Android Sdcard,Buttonclick,我正在开发一个Android应用程序,允许用户将数据(输入和输出)保存到文件中,比如外部SD卡上。与其使用多个“保存”按钮,不如使用复选框“勾选”自动完成,并通过toast通知用户成功将数据保存到文件中。用户可以选择何时保存数据。代码(带有合适的XML文件)编译成APK包,但程序在实际设备上崩溃 此外,在只有一个Add方法的简单版本中,复选框只允许一个输入/输出条目,如果勾选,则不允许重复输入 我想知道语句CheckBox=(CheckBox)是否findviewbyd(R.id.checkBo

我正在开发一个Android应用程序,允许用户将数据(输入和输出)保存到文件中,比如外部SD卡上。与其使用多个“保存”按钮,不如使用复选框“勾选”自动完成,并通过toast通知用户成功将数据保存到文件中。用户可以选择何时保存数据。代码(带有合适的XML文件)编译成APK包,但程序在实际设备上崩溃

此外,在只有一个Add方法的简单版本中,复选框只允许一个输入/输出条目,如果勾选,则不允许重复输入

我想知道语句
CheckBox=(CheckBox)是否findviewbyd(R.id.checkBox1)是否需要声明为类语句?谢谢你的帮助

// import etc. goes here
public class MainActivity extends Activity
{
    private static final int READ_BLOCK_SIZE = 100;
    final Context context = this;
    private Button button;
    //initialize objects as class objects
    TextView result = (TextView) findViewById(R.id.result);
    EditText et1 = (EditText) findViewById(R.id.editText1);
    TextView result2 = (TextView) findViewById(R.id.result2);
    EditText et2 = (EditText) findViewById(R.id.editText2);

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

        button = (Button) findViewById(R.id.buttonShowCustomDialog);

        //add button listener
        button.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View arg0)
            {

                // custom dialog
                final Dialog dialog = new Dialog(context);
                dialog.setContentView(R.layout.custom);
                dialog.setTitle("About My App");

                // set the custom dialog components - text, image and button
                TextView text = (TextView) dialog.findViewById(R.id.text);
                text.setText("This App works!");
                ImageView image = (ImageView) dialog.findViewById(R.id.image);
                image.setImageResource(R.drawable.ic_launcher);

                Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
                // if button is clicked, close the custom dialog
                dialogButton.setOnClickListener(new OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        dialog.dismiss();
                    }
                });

                dialog.show();
            }

        });

    }

    //This method is called when we click on add button
    //and it is declare in main XML file in button tag
    //we have to pass View object in this method

    public void add(View v)
    {

        // in a simpler application the objects et1, result were initialised locally

        String Test = et1.getText().toString();
        if (Test.trim().equals(""))
        {
            Toast.makeText(MainActivity.this, "Please input a number", Toast.LENGTH_SHORT).show();
            return;
        }

        //get text from edit text boxes and convert into double
        double a = Double.parseDouble(String.valueOf(et1.getText()));

        //some maths,  whatever you like to use....
        double b = (a + 100) / 5;

        result.setText("Answer:" + b);

        //---CheckBox---
        CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
        checkBox.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                String strA = et1.getText().toString();
                String strB = result.getText().toString();
                String strC = "Data: " + strA + " " + strB + " ";
                if (((CheckBox) v).isChecked())

                    try
                    {
                        File sdCard = Environment.getExternalStorageDirectory();
                        File directory = new File(sdCard.getAbsolutePath() + "/MyFiles");
                        if (!directory.exists())
                        {
                            directory.mkdirs();
                        }

                        File file = new File(directory, "textfile.txt");
                        if (!file.exists())
                        {
                            file.createNewFile();
                        }
                        FileOutputStream fOut = new FileOutputStream(file, true);

                        OutputStreamWriter osw = new OutputStreamWriter(fOut);

                        //---write the string to the file---
                        osw.append(strC);
                        osw.flush();
                        osw.close();

                        //---display file saved message---
                        Toast.makeText(MainActivity.this, "Data added", Toast.LENGTH_SHORT).show();

                    }
                    catch (IOException ioe)
                    {
                        ioe.printStackTrace();
                    }

            }

        });

    }

    public void add2(View v)
    {

        String TestB = et2.getText().toString();
        if (TestB.trim().equals(""))
        {
            Toast.makeText(MainActivity.this, "Please input a number", Toast.LENGTH_SHORT).show();
            return;
        }

        // get text from edit text boxes and convert into double
        double a2 = Double.parseDouble(String.valueOf(et2.getText()));

        double b2 = (a2 * 100) / 5;

        result2.setText("Answer:" + b2);

        //---CheckBox---
        CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
        checkBox.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                String strD = et2.getText().toString();
                String strE = result.getText().toString();
                String strF = "Data 2: " + strD + " " + strE + " ";
                if (((CheckBox) v).isChecked())

                    try
                    {
                        File sdCard = Environment.getExternalStorageDirectory();
                        File directory = new File(sdCard.getAbsolutePath() + "/MyFiles");
                        if (!directory.exists())
                        {
                            directory.mkdirs();
                        }

                        File file = new File(directory, "textfile.txt");
                        if (!file.exists())
                        {
                            file.createNewFile();
                        }
                        FileOutputStream fOut = new FileOutputStream(file, true);

                        OutputStreamWriter osw = new OutputStreamWriter(fOut);

                        //---write the string to the file---
                        osw.append(strF);
                        osw.flush();
                        osw.close();

                        //---display file saved message---
                        Toast.makeText(MainActivity.this, "Data added", Toast.LENGTH_SHORT).show();

                    }
                    catch (IOException ioe)
                    {
                        ioe.printStackTrace();
                    }

            }

        });

    }
}
相应地进行了修改。谢谢你的提示。作为响应,在应用程序中输入数字后,勾选复选框并单击GUI按钮(应用程序崩溃),以下是设备模拟器上的LogCat输出:


首先,您应该在
onCreate
方法中初始化gui元素,而不是在声明期间:

    // declare GUI components
    private Button button;
    private TextView result;
    private EditText et1;
    private TextView result2;
    private EditText et2;

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

        result = (TextView) findViewById(R.id.result);
        et1 = (EditText) findViewById(R.id.editText1);
        result2 = (TextView) findViewById(R.id.result2);
        et2 = (EditText) findViewById(R.id.editText2);

        button = (Button) findViewById(R.id.buttonShowCustomDialog);
        // ... the rest on onCreate()
    }
为了写入外部存储器,您还需要在
AndroidManifest.xml
文件中注册适当的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

不能在声明部分初始化视图。它必须位于
onCreate()
方法上。所以移动这条线

TextView result = (TextView) findViewById(R.id.result);
EditText et1 = (EditText) findViewById(R.id.editText1);
TextView result2 = (TextView) findViewById(R.id.result2);
EditText et2 = (EditText) findViewById(R.id.editText2);

onCreate()
方法上。

请也共享崩溃的堆栈跟踪,以便我们能提供更大的帮助。问题的根源在于
add
方法,其中命令会引发NPE。您在
MainActivity.java:106的代码中有什么内容?请将gui组件初始化移动到您的
onCreate
方法,并在类主体中保留声明。看看我对什么肯定出了问题的回答。
TextView result = (TextView) findViewById(R.id.result);
EditText et1 = (EditText) findViewById(R.id.editText1);
TextView result2 = (TextView) findViewById(R.id.result2);
EditText et2 = (EditText) findViewById(R.id.editText2);