簡體   English   中英

使用Android FileProvider刪除文件時出現NullPointerException

[英]NullPointerException when deleting file with Android FileProvider

我在使用Android File API時無法正常工作。

這是我要實現的目標,我正在從亞馬遜下載視頻,這些視頻在完全下載后應保存在本地。 我正在以相當簡單的方式執行此操作(代碼已縮短,我只顯示了基本行):

inputStream = connection.getInputStream();
fileOutputStream = context.openFileOutput("my_video", Context.MODE_PRIVATE);
// Read bytes (and store them) until there is nothing more to read(-1)
do {
    int numread = inputStream.read(buffer);
    if (numread <= 0){
        break;                  
    }
    fileOutputStream.write(buffer, 0, numread);
} while (true);

其中inputStreamfileOutputStream是實例變量。

如果視頻完全下載,這實際上效果很好。 在這種情況下,一切都很好,之后我可以在本地訪問視頻。

但是,在應用程序中可能會發生視頻下載中斷並因此需要取消的情況。 如果是這種情況,我想刪除那里但顯然不完整的文件。

刪除文件的代碼如下:

FileProvider fileProvider = new FileProvider();
File newFile = new File(context.getFilesDir(), "my_video");     
Uri contentUri = FileProvider.getUriForFile(context, FILE_PROVIDER, newFile);
fileProvider.delete(fileToDelete, null, null);

最后一行fileProvider.delete(fileToDelete, null, null); 拋出NullPointerException ,我對其進行了調試,並看到fileProvider已初始化,因此我強烈認為我用來調用delete的URI存在問題,但我不知道它是怎么了。 有誰知道如何使用文件提供程序進行正確的刪除?

更新:我希望這並不過分,我現在發布整個VideoDownloader類:

public class VideoDownloader {

  private final int TIMEOUT_CONNECTION = 5000;//5sec
  private final int TIMEOUT_SOCKET = 30000;//30sec

  private static final String FILE_PROVIDER = "com.orangewise.fileprovider";

  private Context context;
  private String videoURL;
  private String targetFileName;

  private HttpURLConnection connection;
  private InputStream inputStream;
  private FileOutputStream fileOutputStream;

  private boolean downloadFinished;

  public VideoDownloader(Context context, String videoURL, String targetFileName) {
    this.context = context;
    this.videoURL = videoURL;
    this.targetFileName = targetFileName;
    this.downloadFinished = false;
  }

  public boolean isDownloadFinished(){
    return this.downloadFinished;
  }

  public void startDownload(){
    downloadVideoFile(this.context, this.videoURL, this.targetFileName);    
  }

  private void downloadVideoFile(Context context, String videoURL, String targetFileName) {
    URL url = null;
    try {
        url = new URL(videoURL);

        // Open a connection to that URL.
        connection = (HttpURLConnection) url.openConnection();

        connection.setReadTimeout(TIMEOUT_CONNECTION);
        connection.setConnectTimeout(TIMEOUT_SOCKET);r

        inputStream = connection.getInputStream();
        fileOutputStream = context.openFileOutput(targetFileName, Context.MODE_PRIVATE);

        byte[] buffer = new byte[3 * 1024];
        int counter = 0;

        // Read bytes (and store them) until there is nothing more to read(-1)
        do {
            int numread = inputStream.read(buffer);
            if (numread <= 0){
                break;                  
            }
            fileOutputStream.write(buffer, 0, numread);
        } while (true);
        downloadFinished = true;

        // Clean up
        closeStreams();
    } catch (Exception e) {
        Log.d(Constants.ERROR, "ERROR [" + getClass().getName() + "]: Caught exception (" + e + ") when trying to download video: " + e.getMessage());
    }
  }

  public Uri getUriForFile(){
    return getUriForFile(context, targetFileName);
  }

  private Uri getUriForFile(Context context, String fileName){

    File newFile = new File(context.getFilesDir(), fileName);       
    Uri contentUri = FileProvider.getUriForFile(context, FILE_PROVIDER, newFile);

    return contentUri;
  }

  public void cancel(){
    // 1. cancel the connection
    Log.d(Constants.LOG, "DEBUG [" + getClass().getName() + "]: Cancel connection");

    try {
        connection.disconnect();
        closeStreams();

        if(!isDownloadFinished()){              
            // Remove the file if it has not been fully downloaded
            FileProvider fileProvider = new FileProvider();
            Uri fileToDeleteUri = getUriForFile();
            fileProvider.delete(fileToDeleteUri, null, null); // returns 1 if the delete succeeds; otherwise, 0.
        }
        else{
            Log.d(Constants.LOG, "DEBUG [" + getClass().getName() + "]: Leave the file, it has been completely download");
        }
    } 
    catch (Exception e) {
        Log.d(Constants.ERROR, "Exception ( " + e + " ) caught: " +  e.getMessage() + "; ");
    }
}

private void closeStreams() throws IOException{     
    // Close the streams
    try {           
        fileOutputStream.flush();
        fileOutputStream.close();
        inputStream.close();
    } catch (NullPointerException e) {
        Log.d(Constants.ERROR, "Null pointer exception caught: " +  e.getMessage());
    }
    Log.d(Constants.LOG, "DEBUG [" + getClass().getName() + "]: Clean up performed");
  }
} 

另一個更新:這是我的堆棧跟蹤:

07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152): java.lang.NullPointerException
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at android.support.v4.content.FileProvider.delete(FileProvider.java:497)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at com.orangewise.just4kidstv.util.VideoDownloader.cancel(VideoDownloader.java:134)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at com.orangewise.just4kidstv.util.VideoDownloadTask.cancel(VideoDownloadTask.java:20)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at com.orangewise.just4kidstv.activities.VideoPlayerActivity.onStop(VideoPlayerActivity.java:64)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1170)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at android.app.Activity.performStop(Activity.java:3873)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:2623)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:2694)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at android.app.ActivityThread.access$2100(ActivityThread.java:117)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:968)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at android.os.Looper.loop(Looper.java:130)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at android.app.ActivityThread.main(ActivityThread.java:3687)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at java.lang.reflect.Method.invokeNative(Native Method)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at java.lang.reflect.Method.invoke(Method.java:507)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
07-23 17:31:29.114: E/com.organgewise.just4kidstv.LOG(6152):    at dalvik.system.NativeStart.main(Native Method)

檢查sdk Extras中隨附的v4支持庫的FileProvider.java的源,我們發現:

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
   // ContentProvider has already checked granted permissions
   final File file = mStrategy.getFileForUri(uri);   /* line 497 */
   return file.delete() ? 1 : 0;
}

因此,mStrategy為空。

進一步搜索,我們發現它僅在一個地方被初始化:

/**
 * After the FileProvider is instantiated, this method is called to provide the system with
 * information about the provider.
 *
 * @param context A {@link Context} for the current component.
 * @param info A {@link ProviderInfo} for the new provider.
 */
@Override
public void attachInfo(Context context, ProviderInfo info) {
    super.attachInfo(context, info);

    // Sanity check our security
    if (info.exported) {
        throw new SecurityException("Provider must not be exported");
    }
    if (!info.grantUriPermissions) {
        throw new SecurityException("Provider must grant uri permissions");
    }

    mStrategy = getPathStrategy(context, info.authority);
}

因此很明顯,您的FileProvider 尚未通過調用此方法正確設置。

FileProvider 文檔尚不十分清楚,但似乎您不應該簡單地執行“ new FileProvider()”,而應該在清單中進行一些相關的設置。

@克里斯·斯特拉頓是正確的。 您不應使用該構造函數實例化它。 FileProvider是ContentProvider的子類。 由於您在AndroidManifest.xml中聲明了它,因此可以使用以下方法獲取它的句柄:

context.getContentResolver()

因此,您可以通過執行以下操作來修復NullPointerException:

context.getContentResolver().delete(contentUri, null, null);

您可以檢查它返回1以確認它是否起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM