0

我在写入文件时遇到问题,当 EditText 为空时,我想写一个空格字符或-在我的文件中,但我的条件被简单地忽略了。

这不起作用,我不明白为什么:

public void onClick(View v) {
            // TODO Auto-generated method stub
            if(isthereafile == true){
            questioncount++;
            questiontext = question.getText().toString();
            correctanswertext = correctanswer.getText().toString();
            wronganswertext1 = wronganswer1.getText().toString();
            wronganswertext2 = wronganswer2.getText().toString();
            textpathofpic = pathofpic.getText().toString();

            try {
                FileWriter writer = new FileWriter(test,true);

                if(question.getText().toString().equals("") == false){
                writer.append(questiontext + ";");}
                if(correctanswer.getText().toString().equals("") == false){
                writer.append(correctanswertext + ";");}
                if(wronganswer1.getText().toString().equals("") == false){
                writer.append(wronganswertext1 + ";");}
                if(wronganswer2.getText().toString().equals("") == false){
                writer.append(wronganswertext2 + ";");}
                if(pathofpic.getText().toString().equals("") == false){
                writer.append(textpathofpic + ";");}

                if(question.getText().toString().equals("")){writer.append("-");}
                if(correctanswer.getText().toString().equals("")){writer.append("-");}
                if(wronganswer1.getText().toString().equals("")){writer.append("-");}
                if(wronganswer2.getText().toString().equals("")){writer.append(" ");}
                writer.flush();
                writer.close();     
                question.setText("");           
                correctanswer.setText("");      
                wronganswer1.setText("");           
                wronganswer2.setText("");

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }

        }
    });
4

2 回答 2

0

除了检查长度之外,您还需要修剪文本:

if (question.getText().toString().trim().length() == 0) {
}

一个更大的问题是您的代码在主线程上写入文件系统。您也不会在 finally 块中关闭 FileWriter。并且不需要在 close() 之前立即调用 flush()。

于 2012-04-28T14:51:47.880 回答
0

而不是这个

  question.getText().toString().equals("")   

试试这样

  question.getText().toString().length()==0
于 2012-04-28T14:35:33.140 回答