gpt4 book ai didi

java - Context.getContentResolver().query() 给出空指针异常

转载 作者:行者123 更新时间:2023-12-05 07:50:09 24 4
gpt4 key购买 nike

我正在做一个音乐项目,我正在使用歌曲的 ID 来找出它的标题。这是我用来这样做的功能。它在 MetadataFinder 类中。

public static String getSongFromID(long id, Context context) {
Uri mediaContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = new String[]{MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE};
String selection = MediaStore.Audio.Media._ID + "=?";
String[] selectionArgs = new String[]{"" + id}; //This is the id you are looking for

Cursor mediaCursor = context.getContentResolver().query(mediaContentUri, projection, selection, selectionArgs, null);

if (mediaCursor.getCount() >= 0) {
mediaCursor.moveToPosition(0);
String title = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
return title;
//Do something with the data
}
return null;
}

到目前为止,这非常有效。但是现在,当我从代码的另一部分调用此方法时,它给出了空指针异常。

我有两个 fragment ,从那里我向主要 Activity 发送广播。主要 Activity 广播接收器调用服务中的一个函数,我们称之为 MainService。服务中的这个方法调用了上面的方法getSongFromID。我正在从两个 fragment 中调用此方法。对于“id”和上下文“MainService.this”的相同值,我在一种情况下遇到异常,而另一种情况下工作正常。

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.database.Cursor.getCount()' on a null object reference
at com.app.utils.MetadataFinder.getSongFromID(CommonUtils.java:331)
at com.app.services.MainService.playSong(MainService.java:189)
at com.app.activity.MainActivity.initPanelBottom(MainActivity.java:235)
at com.app.activity.MainActivity$1.onReceive(MainActivity.java:155)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

我不明白这背后的原因可能是什么,因为我看不出任何涉及的参数有什么不同。有人可以帮帮我吗!!

String title = MetadataFinder.getSongFromID(i, MainService.this);

这就是我调用 getSongFromId() 函数的方式。它是 MetadataFinder 类中的一个静态函数。

最佳答案

感谢 Nguyen's 的建议,我终于能够解决我的问题。我在所有忘记关闭的地方关闭了光标,最终一切正常。

关于java - Context.getContentResolver().query() 给出空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36477149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com