gpt4 book ai didi

java - 从 runnable 调用函数

转载 作者:太空宇宙 更新时间:2023-11-04 14:44:46 25 4
gpt4 key购买 nike

我在Android应用程序中有一段代码,它是Runnable的实现。在方法 void run() 的实现中,我在 Activity 本身内部、Runnable 实现之外调用了一个函数。

代码如下:

Message msg = Message.obtain(null, Communicator.MSG_REFRESH_ASSIGNED_LOCATIONS, 
new Runnable() {

@Override
public void run() {
Cursor assignedLocations = getAssignedLocations();
assignedLocations.moveToFirst(); //EXCEPTION HERE! NULL POINTER EXCEPTION!!
if(!assignedLocations.isAfterLast()) {
//some code
} else {
//some code
}
}
});

该函数是getAssignedLocations(),它从查询返回一个游标到sqlite。

当从 Runnable 实现外部(即从 onResume 或 onCreate)调用时,getAssignedLocations() 函数可以正常工作并且不会返回 null。

以下是 getAssignedLocations() 的代码:

/**
* returns a cursor for all assigned locations in the local database
* @return
*/
protected Cursor getAssignedLocations() {
return getAssignedLocations(null);
}

/**
* returns a cursor from the database with only one entry of which the loc_id is specificLoaction
* if specificLocation is null, returns all assigned locations from the database
* @param specificLocation
* @return
*/
private Cursor getAssignedLocations(String specificLocation) {
SQLiteDatabase db = personalLocations.getReadableDatabase();
String[] projection = {
FeedEntry.COLUMN_NAME_LOC_ID,
FeedEntry.COLUMN_NAME_LOC_NAME
};

String orderBy =
FeedEntry.COLUMN_NAME_LOC_NAME + " DESC";

if(specificLocation == null) {
Cursor c = db.query(FeedEntry.TABLE_NAME, projection, null, null, null, null, orderBy);
return c;
}

String[] arguments = {specificLocation};

Cursor c = db.query(FeedEntry.TABLE_NAME, projection, FeedEntry.COLUMN_NAME_LOC_ID + "=?", arguments, null, null, orderBy);
return c;
}

任何人都可以解释为什么我会收到空​​指针异常吗?将非静态函数传递给 Runnable 接口(interface)是否不起作用?

最佳答案

感谢 setthro 的大力帮助,我们共同发现错误出在代码的另一部分,甚至没有包含在问题中。

我使用了错误的 Message.obtain 方法,因此将 Runnable 实现放在 Message.obj 而不是 Message.getCallback() 中。所以当我调用它来获取服务中的Runnable时,它返回了null。空指针异常实际上就是从那里开始的。

对于 future 的人来说,当您使用 message.obtain 时,这可能是需要注意的事情。它的一些变体接受 Object,因此当您在那里放置错误的参数时不会警告您。

C++ 程序员可能会 mock 我们遇到麻烦:-)

关于java - 从 runnable 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24541603/

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