I am making a music player app and when opening any song from files it comes like this Uri
/external/audio/media/1162591
and when I try to convert this Uri with this code
private String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
It returns error and this is the logcat
2021-06-07 22:58:47.612 6898-6898/com.yapps.ymusic E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.yapps.ymusic, PID: 6898
java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=1, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.yapps.ymusic/com.yapps.ymusic.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int android.database.Cursor.getColumnIndexOrThrow(java.lang.String)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:5041)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5084)
at android.app.ActivityThread.-wrap20(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
at android.os.Handler.dispatchMessage(Handler.java:108)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.database.Cursor.getColumnIndexOrThrow(java.lang.String)' on a null object reference
at com.yapps.ymusic.MainActivity.getRealPathFromURI(MainActivity.java:752)
at com.yapps.ymusic.MainActivity.StringSound(MainActivity.java:740)
at com.yapps.ymusic.MainActivity.onRequestPermissionsResult(MainActivity.java:677)
at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:7854)
at android.app.Activity.dispatchActivityResult(Activity.java:7705)