2012-06-26 75 views
1

我試圖讓用戶選擇一個音頻文件並存儲該音頻文件的路徑。我通過使用ACTION_GET_CONTENT Intent這樣做,因此用戶可以選擇一個應用程序來選擇文件。由於某些原因,在onActivityResult方法中,意圖數據返回爲null,如錯誤消息中所示。 Logcat錯誤信息和相關代碼如下。任何幫助將不勝感激。Android:失敗傳遞結果ResultInfo。意圖顯然是空的?

主要編輯: - 這個錯誤只有當我按下後退按鈕或刪除發生!選擇音樂文件實際上工作正常。對於那個很抱歉。儘管如此,錯誤仍然存​​在。

logcat的錯誤: -

06-26 16:36:25.238: E/AndroidRuntime(24759): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=0, data=null} to activity {com.packagename.appname.activityname}: java.lang.NullPointerException 

電話放置在一個方法選擇器的活性,其在的onCreate()調用: -

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
intent.setAction(Intent.ACTION_PICK); 
intent.setType("audio/*"); 
startActivityForResult(intent, audioreminder); 

onActivityResult()方法: -

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    SharedPreferences flags = this.getSharedPreferences(
      "screen_on_flags", MODE_WORLD_READABLE); 
    SharedPreferences.Editor editor = flags.edit(); 
    String FilePath = data.getData().getPath(); 
    switch (requestCode) { 
    case audioreminder: { 
     if (resultCode == RESULT_OK) { 
      editor.putString("audioreminderpath", FilePath); 
      editor.commit(); 
     } else if (resultCode == RESULT_CANCELED){ 
      CheckBoxPreference other_audioreminder = (CheckBoxPreference) findPreference("other_audioreminder"); 
      other_audioreminder.setChecked(false); 
      } 
     break; 
    } 
    } 
} 

回答

3

我用過,這個代碼..

Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI); 
startActivityForResult(Intent.createChooser(intent, "Gallery"), audioreminder); 

此外,在onActivityResult()檢查Intent data要麼是空或不是

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    if(data != null) 
    { 
    SharedPreferences flags = this.getSharedPreferences(
      "screen_on_flags", MODE_WORLD_READABLE); 
    SharedPreferences.Editor editor = flags.edit(); 
    String FilePath = data.getData().getPath(); 
    switch (requestCode) { 
    case audioreminder: { 
     if (resultCode == RESULT_OK) { 
      editor.putString("audioreminderpath", FilePath); 
      editor.commit(); 
     } else if (resultCode == RESULT_CANCELED){ 
      CheckBoxPreference other_audioreminder = (CheckBoxPreference) findPreference("other_audioreminder"); 
      other_audioreminder.setChecked(false); 
      } 
     break; 
    } 
    } 
    } 
else 
{ 
Log.e("Intent data:" , "null") 
} 
} 

試試這個,讓我知道發生什麼事..

+1

然後只是檢查** Intent數據不是null **在onActivityResult()中,正如我在我的答案中所述。 – user370305

+0

感謝您的快速回復。我試過代碼,日誌的確顯示Intent數據爲空。不再有強制關閉,但不幸的是,這意味着else if語句中的代碼(例如,resultCode == RESULT_CANCELED)將永遠不會執行。我想我可以將代碼轉移到日誌語句所在的位置,它就可以工作。任何想法爲什麼數據爲空? =)再次感謝您的時間。你已經回答了我的問題,所以我選擇它作爲回答^^ –

+0

其實,resultCode爲== RESULT_CANCELED是工作,但在你的情況你之前獲得意圖數據,所以其造成的異常.. – user370305

0

沒有什麼錯誤說的是,你的onActivityResult()方法拋出NullPointerException,而不是數據必然是null。您需要進行調試以查看錯誤在您的方法中的位置。

相關問題