2014-11-03 129 views
0

即時通訊開發一個應用程序下載圖像到用戶phones.the下載部分正常工作,圖像存儲在「/ Android/data/files /」。我首先做一個檢查,看看文件是否存在,如果沒有,那麼我想下載它。但是當我運行應用程序時,它一直在拋出一個NullpointerException。這是因爲在第一次運行時不存在「/ Android/data //文件/」?如果是這樣,我該如何解決此問題。如何檢查目錄是否存在文件?

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    testtv = (TextView) findViewById(R.id.testtv); 
    String imagename = "/img11.png"; 
    File image = new File(Environment.getExternalStorageDirectory() 
      .getAbsolutePath() 
      + "/Android/data/com.id.imagedownloader/files" + imagename); 
    // testtv.setText(image.toString()); 

    if (image.exists()) { 
     testtv.setText("file exists"); 
    } else { 
     Boolean result = isDownloadManagerAvailable(getApplicationContext()); 
     if (result) { 
      downloadFile(imagename); 
     } 
    } 

} 

@SuppressLint("NewApi") 
public void downloadFile(String imagename) { 
    // TODO Auto-generated method stub 
    String DownloadUrl = "http://testing16.comlu.com/images/" + imagename; 
    DownloadManager.Request request = new DownloadManager.Request(
      Uri.parse(DownloadUrl)); 
    request.setDescription("sample file for testing"); // appears the same 
                 // in Notification 
                 // bar while 
                 // downloading 
    request.setTitle("Test Title"); 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
     request.allowScanningByMediaScanner(); 
     request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
    } 
    String fileName = DownloadUrl.substring(
      DownloadUrl.lastIndexOf('/') + 1, DownloadUrl.length()); 
    request.setDestinationInExternalFilesDir(getApplicationContext(), null, 
      fileName); 

    // get download service and enqueue file 
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); 
    manager.enqueue(request); 

} 

public static boolean isDownloadManagerAvailable(Context context) { 
    try { 
     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { 
      return false; 
     } 
     Intent intent = new Intent(Intent.ACTION_MAIN); 
     intent.addCategory(Intent.CATEGORY_LAUNCHER); 
     intent.setClassName("com.android.providers.downloads.ui", 
       "com.android.providers.downloads.ui.DownloadList"); 
     List<ResolveInfo> list = context.getPackageManager() 
       .queryIntentActivities(intent, 
         PackageManager.MATCH_DEFAULT_ONLY); 
     return list.size() > 0; 
    } catch (Exception e) { 
     return false; 
    } 
} 

logcat的

11-03 14:13:35.821: E/AndroidRuntime(771): FATAL EXCEPTION: main 
11-03 14:13:35.821: E/AndroidRuntime(771): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.id.imagedownloader/com.id.imagedownloader.MainActivity}: java.lang.NullPointerException: file 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.ActivityThread.access$600(ActivityThread.java:122) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.os.Handler.dispatchMessage(Handler.java:99) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.os.Looper.loop(Looper.java:137) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.ActivityThread.main(ActivityThread.java:4340) 
11-03 14:13:35.821: E/AndroidRuntime(771): at java.lang.reflect.Method.invokeNative(Native Method) 
11-03 14:13:35.821: E/AndroidRuntime(771): at java.lang.reflect.Method.invoke(Method.java:511) 
11-03 14:13:35.821: E/AndroidRuntime(771): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
11-03 14:13:35.821: E/AndroidRuntime(771): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
11-03 14:13:35.821: E/AndroidRuntime(771): at dalvik.system.NativeStart.main(Native Method) 
11-03 14:13:35.821: E/AndroidRuntime(771): Caused by: java.lang.NullPointerException: file 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.net.Uri.fromFile(Uri.java:441) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.DownloadManager$Request.setDestinationFromBase(DownloadManager.java:504) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.DownloadManager$Request.setDestinationInExternalFilesDir(DownloadManager.java:466) 
11-03 14:13:35.821: E/AndroidRuntime(771): at com.id.imagedownloader.MainActivity.downloadFile(MainActivity.java:63) 
11-03 14:13:35.821: E/AndroidRuntime(771): at com.id.imagedownloader.MainActivity.onCreate(MainActivity.java:40) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.Activity.performCreate(Activity.java:4465) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 
11-03 14:13:35.821: E/AndroidRuntime(771): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919) 
11-03 14:13:35.821: E/AndroidRuntime(771): ... 11 more 
+1

也許'嘗試{...} catch(IOException e){...}' – jyoon 2014-11-03 08:52:58

+0

是不是來自方法downloadFile的異常? com.id.imagedownloader.MainActivity.downloadFile(MainActivity.java:63),所以如果你在外部存儲設置目的地,確保該文件夾存在,那麼這應該工作(至少從我看到的) – Michael 2014-11-03 08:57:14

+0

它不保證存在外部存儲器 – for3st 2014-11-03 08:57:49

回答

0

設置本地目的地下載的文件的路徑應用程序的外部文件中的目錄

request.setDestinationInExternalFilesDir(context,Environment.DIRECTORY_DOWNLOADS,image); 

不要忘記創建mkdirs迪爾斯()如果父文件夾不存在

+0

我用下載功能更新了代碼 – 2014-11-03 09:02:10

0

setDestinationInExternalFilesDir需要dirType參數。你應該這樣使用它:

request.setDestinationInExternalFilesDir(getApplicationContext(), Environment.DIRECTORY_DOWNLOADS, 
     fileName); 
-1

有了這個功能,你可以創建一個從字節數組文件,並檢查是否存在這樣。嘗試這樣的:

/** 
* Create new file from byte array 
* @param path 
* @param array source 
* @throws IOException 
*/ 
public static void writeFile(String path, byte[] array) throws IOException { 
    File file = new File(path); 
    if (!file.exists() && array != null) { 
     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); 
     bos.write(array); 
     bos.flush(); 
     bos.close(); 
    } else { 
     // the file exists... 

    } 
} 

希望它能幫助你!

+0

我剛剛在我運行CM11的GS3上測試了我的代碼,它工作正常..它只在模擬器中崩潰。爲什麼? – 2014-11-03 11:58:17

+0

如果嘗試將文件保存在外部存儲器中,可能會因此而崩潰。 – 2014-11-03 12:24:11

+0

你可以添加logcat跟蹤嗎? – 2014-11-03 13:04:14

相關問題