开发者

Weird NullPointerException Error

I've this snippet:

Log.d("iBank", "Helper: " + helper.toString());
Log.d("iBank开发者_StackOverflow社区", "File: " + file.toString());
if(helper.read(file).equals(""))
{
    dataDir = Environment.getExternalStoragePublicDirectory(
          Environment.DIRECTORY_DOWNLOADS);
}
else
{
    dataDir = new File( helper.read(file) );
}

My problem is, it always throws NullPointerException on if(helper.read(file).equals("")). I did Log.d() on both object (like you see on above code) but it didn't throws that exeption. At first, I though it's something wrong on helper.read(). But, as you see below, I have already catch possible error:

public String read(File file)
{
    if(file == null)
        return "";
    String data = "";
    if( !file.exists())
    {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        FileReader fr = new FileReader(file);
        BufferedReader bfr = new BufferedReader(fr);
        data = bfr.readLine();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return data;
}

I'm not sure what's wrong with my code. Maybe I miss something, but I can't figure it out.

UPDATE

I fix my code to return (data == null) ? "" : data;


I think bfr.readLine(); is returning null so helper.read(file) is null.

BufferedReader's readline returns the contents of the line or null if no characters were read before the end of the reader has been reached.

Are you sure the file is not empty. file.toString() converts the file object to string representation but you wouldnt know whether the file is empty or not.


Instead of logging, try to debug and see whats really going on...

My guess: while debugging you will see that bfr.readLine() returns null which is stored in data. That results in read() returning null, too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜