2016-01-24 40 views
0

我無法讀取或寫入我的Android設備。在同一主題上有類似的問題(我已經實現了代碼),但它們似乎都會讓我的應用崩潰。無法以編程方式將文件夾或文件寫入Android設備

Button btnUpload = (Button) findViewById(R.id.btnUpload); 
File created = new File(Environment.getExternalStorageDirectory().getPath() 
         + File.separator + "MyNewFolder" + File.separator + "created");  

if (created.isDirectory()) {  
    File[] contents = created.listFiles(); 

    //Should not trigger as directory check is in place 
    if (contents == null) {   //<--not adding this section causes a crash 
     btnUpload.setEnabled(false); 
    } 

    //Check to see if the number of files is 0 
    else if (contents.length == 0) { 
     btnUpload.setEnabled(false); 
    } 

    //All checks pass. Enable button 
    else { 
     btnUpload.setEnabled(true); 
    } 
} 
  • 清單文件具有「WRITE_EXTERNAL_STORAGE」權限添加
  • 保證了電話(Nexus 5上,與棉花糖)是調試模式和「文件傳輸」模式被選擇。
+1

看看[這篇文章](http://stackoverflow.com/questions/32635704/cant-get-the-permission)。 –

+1

使用LogCat檢查與您的崩潰相關的Java堆棧跟蹤:https://stackoverflow.com/questions/23353173/uncomfort-myapp-has-stopped-how-can-i-solve-this如果您無法理解堆棧跟蹤,編輯您的問題以提供該問題,以及您在創建此目錄的清單和代碼。而且,正如Mike所說,如果你的'targetSdkVersion'是23或者更高,那麼一定要在運行時向你的代碼顯示你要求的'WRITE_EXTERNAL_STORAGE'。 – CommonsWare

回答

0

非常感謝Mike和Commonwares。

摘要:隨着Manifest文件中的權限,我們需要在運行時檢查權限(並在缺少時請求它們)。問題在於API級別23.

根據某些閱讀添加了兩行代碼。不會是最好的或遵循所有最佳編碼實踐,而是一個快速和骯髒的解決方案,所以請相應修改。

if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { 
     requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); 
    } 

我已將此添加到我的主要活動的開始,以便我可以在剩下的時間內獲得許可權及其設置。

+0

請求權限盡可能接近實際使用情況。 – gilgil28

相關問題