1

我试图让用户选择一个音频文件并存储该音频文件的路径。我这样做是通过使用ACTION_GET_CONTENT Intent来实现的,这样用户就可以选择一个应用程序来选择文件。但由于某种原因,在onActivityResult方法中,Intent 数据以null形式返回,如错误消息中所示。Logcat 错误信息和相关代码如下。任何帮助将不胜感激。

主要编辑:-此错误仅在我按下后退按钮或取消时发生!选择音乐文件实际上工作正常。对于那个很抱歉。尽管如此,错误仍然存​​在。

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;
    }
    }
}
4

2 回答 2

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")
 }
}

试试这个,让我知道会发生什么..

于 2012-06-26T12:50:20.530 回答
0

不,错误说的是您的onActivityResult()方法抛出了 a NullPointerException,而不是数据必然是null。您需要调试以查看错误在您的方法中的位置。

于 2012-06-26T12:47:23.420 回答