java - ContextWrapper.getFilesDir() 出现 NullPointerException 的原因

标签 java android nullpointerexception

我已在 Google Play 中发布了我的应用,并且收到了一位用户的崩溃报告。不幸的是,由于匿名原因,我没有记者的联系方式,因此无法获得有关坠机事件的更多详细信息。我只掌握了报告中的异常详细信息。下面是抛出异常的函数。异常在以下行抛出:

File dbDir = new File(this.getFilesDir().getPath()+"/database");

我试图找出为什么上面的行会抛出 NullPointerException 。

欢迎任何建议。

完整功能如下:

private void ensureDBAvailable() throws IOException{
            // The NullPointerException was thrown in the line below
    File dbDir = new File(this.getFilesDir().getPath()+"/database");
    if (!(dbDir.mkdirs() || dbDir.isDirectory()))
    {
        //This should never happen, in this case the caller should stop the service
        throw(new IOException("Cannot create database directory"));
    }

    File dbFile = new File(dbDir, MainService.DB_FILENAME);

    if(!dbFile.exists())
    {
        InputStream dbFromApk = null; 
        OutputStream dbout = null;

        try
        {
            dbFromApk = this.getAssets().open(DB_FILENAME, AssetManager.ACCESS_STREAMING);

            //the database file does not exist, let's get it from the APK. 
            dbout = new FileOutputStream(dbFile);

            byte[] buffer = new byte[1024];
            int bytesRead = 0;

            while((bytesRead = dbFromApk.read(buffer))> 0)
            {
                dbout.write(buffer, 0, bytesRead);
            }
        }
        finally
        {
            dbFromApk.close();
            dbout.close();
        }
    }
}

最佳答案

getFilesDir 有时返回 null。 It's bug 。所以你必须检查 getFilesDir 是否返回 null。

关于java - ContextWrapper.getFilesDir() 出现 NullPointerException 的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22596731/

相关文章:

java - REGEX匹配问题

android - 输入中的 Apollo graphQL 不支持的标记

android - ScrollView 在弹出窗口中不起作用

android - 更改 WebView 中的文本颜色?

java - 什么是NullPointerException,我该如何解决?

java - DB 列上的 Spring JPA 错误返回与列名称相关的错误

java - PARSE 中两个用户对象的查询

java - Map.containsValue() 返回 false

java - 为什么我的 JComboBox 返回 null?

java安全不允许我使用Jfilechooser打开拍照