2017-08-11 48 views
0

當我嘗試選擇圖像時,文件選擇器會顯示'相機'和'文件',如果我不選擇它並點擊,它會崩潰? 我已經嘗試了一些答案,但我是一個webdev而不是android dev。幫幫我!當'不'從文件選擇/圖庫中選擇圖像時,應用程序崩潰

這類似於app crashes when going back from gallery without selecting any image

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode != INPUT_FILE_REQUEST_CODE || mUploadMessage == null) { 
     super.onActivityResult(requestCode, resultCode, data); 
     return; 
    } 
    try { 
     String file_path = mCameraPhotoPath.replace("file:",""); 
     File file = new File(file_path); 
     size = file.length(); 

    }catch (Exception e){ 
     Log.e("Error!", "Error while opening image file" + e.getLocalizedMessage()); 
    } 

    if (data != null || mCameraPhotoPath != null) { 
     Integer count = 1; 
     ClipData images = null; 
     try { 
      images = data.getClipData(); 
     }catch (Exception e) { 
      Log.e("Error!", e.getLocalizedMessage()); 
     } 

     if (images == null && data != null && data.getDataString() != null) { 
       count = data.getDataString().length(); 
     } else if (images != null) { 
       count = images.getItemCount(); 
     } 
     Uri[] results = new Uri[count]; 
     // Check that the response is a good one 
     if (resultCode == Activity.RESULT_OK) { 
      if (size != 0) { 
       // If there is not data, then we may have taken a photo 
       if (mCameraPhotoPath != null) { 
        results = new Uri[]{Uri.parse(mCameraPhotoPath)}; 
       } 
      } else if (data.getClipData() == null) { 
       results = new Uri[]{Uri.parse(data.getDataString())}; 
      } else { 

       for (int i = 0; i < images.getItemCount(); i++) { 
        results[i] = images.getItemAt(i).getUri(); 
       } 
      } 
     } 

     mUploadMessage.onReceiveValue(results); 
     mUploadMessage = null; 
    } 
} 
+2

用你正在收到的錯誤更新你的問題 – GuilhermeFGL

回答

5

你沒有做你的計算之前做過任何resultCode長的檢查你的onActivityResult。因爲當您沒有選擇圖片時回來,resultCode爲RESULT_CANCELLED,您的data爲空。張貼在你data任何操作總是會導致空指針異常

做如下 -

if (resultCode==RESULT_OK){ 
    // do stuff here that is the part of your try catch block 
} 

大多是當您試圖在數據這是做data.getDataString()你的代碼崩潰不在那裏。而且考慮到這一點在你的try塊之外,它永遠不會被抓到,應用程序崩潰。

+0

mCameraPhotoPath.replace(「file:」,「」)'如果在活動中死的時候沒有在'Bundle'中存儲也是危險的 –

+2

有一個。這是接近尾聲,可能會遲到做,但有一個 – litelite

+0

是的,現在我看到了。太晚了。謝謝@litelite –

相關問題