2016-07-21 57 views
0

我試圖從服務器下載文件並將其存儲在存儲中,但代碼給出錯誤 - Unable to create directory。請檢查錯誤無法在Android中創建目錄錯誤

任務 - 從服務器下載文件,然後在android的webview中加載它。

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    webView = (WebView) findViewById(R.id.webView); 
    try { 
     webView.loadUrl("file://" + Environment.getExternalStorageDirectory() + "/sponsors/"+ "dddd.html"); 
    } 
    catch (Exception e) 
    { 
     Toast.makeText(MainActivity.this, "File Doesn't Exist", Toast.LENGTH_SHORT).show(); 
    } 
    try { 
     myDownloadLast("http://192.168.76.1:8084/MyTest/dddd.html"); 
    } 
    catch (Exception e) 
    { 
     Toast.makeText(this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_SHORT).show(); 
    } 
} 
public void myDownloadLast(String myURL) { 

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myURL)); 
    request.setTitle("Updating TimeTable"); 
    request.setDescription("Please Wait"); 

    //request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); 
    request.allowScanningByMediaScanner(); 
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
    //request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN); 
    String nameOfFile = URLUtil.guessFileName(myURL, null, MimeTypeMap.getFileExtensionFromUrl(myURL)); 

    File myFile = new File(String.valueOf(Environment.getExternalStoragePublicDirectory("/sponsors/"))); 
    if(!myFile.exists()){ 
     myFile.mkdir(); 
    } 
    try { 
     request.setDestinationInExternalPublicDir(String.valueOf(myFile), nameOfFile); 
    } 
    catch (Exception e) 
    { 
     Toast.makeText(this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_SHORT).show(); 
    } 
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); 
    manager.enqueue(request); 
    BroadcastReceiver onComplete = new BroadcastReceiver() { 
     public void onReceive(Context ctxt, Intent intent) { 
      //Toast.makeText(getActivity(), "Download Complete", Toast.LENGTH_LONG).show(); 
      Toast.makeText(getApplicationContext(), "Update Complete\nFor Best Performance\nRestart The App", Toast.LENGTH_SHORT).show(); 
     } 
    }; 
    registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 
} 
+0

請發佈您的日誌或堆棧跟蹤,如果你h趕走他們。 –

+0

'myFile.mkdir();'。這應該是'if(!myFile.mkdir())return;'並顯示一個toast來通知用戶。 – greenapps

+0

'但代碼給出錯誤'。代碼?請準確。哪些聲明?哪條線? – greenapps

回答

1

你的問題可能與幾個犯罪嫌疑人

確保對Android清單權限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

另外,請參閱外部目錄中的以下內容:

String name = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DirectoryNameYouWant/" ;