我有个问题。我想让我的应用程序的用户使用ACTION_GET_CONTENT从存储中选择一个音频文件,那时我的mainActivity崩溃了。
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,1);
audioPath = intent.getData().getPath(); //This is were the crash happens
audio = Uri.parse(audioPath);
}
我是android编程的新手,肯定有些东西我听不懂。错误如下:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.lang.String android.net.Uri.getPath()'
最佳答案
您必须在活动中覆盖“活动结果”。不要使用与您相同的意图。您必须使用Intent
方法中返回的onActivityResult
。因此,您的代码应为:
这应该是您选择音频的方法
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,1); //This 1 is your request code remember it
}
然后将onActivityResult方法重写为
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
//The intent from this method is the one you need to get data from!
if (requestCode == 1) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
audioPath = intent.getData().getPath();
audio = Uri.parse(audioPath);
}
}
}
有关此方法以及从“活动结果check this official training from Android”接收数据的更多信息。编码愉快!
关于java - 从用户获取uri时我的应用程序崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46809374/