Java 从runnable调用函数
我在Android应用程序中有一段代码,这是Runnable的一个实现。 在方法Java 从runnable调用函数,java,android,sqlite,Java,Android,Sqlite,我在Android应用程序中有一段代码,这是Runnable的一个实现。 在方法void run()的实现中,我调用了活动本身中的一个函数,在可运行实现之外 代码如下所示: Message msg = Message.obtain(null, Communicator.MSG_REFRESH_ASSIGNED_LOCATIONS, new Runnable() { @Override public void run() {
void run()
的实现中,我调用了活动本身中的一个函数,在可运行实现之外
代码如下所示:
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
getAssignedLocations()
函数工作,从Runnable实现外部调用时不返回null(表示从onResume或onCreate调用)
以下是getAssignedLocations()
的代码:
有人能解释为什么我得到一个空指针异常吗?将非静态函数传递给Runnable接口是否不起作用?多亏了sethro的帮助,我们一起发现错误出现在代码的另一部分,甚至没有包含在问题中 我使用了错误的Message.get方法,因此将可运行实现放在Message.obj中,而不是Message.getCallback()。因此,当我调用它以获取服务中的Runnable时,它返回null。空指针异常实际上就是从那里开始的 对于未来的用户,这可能是在使用message.get时需要注意的事项。它的一些变体接受
对象
,因此当您在其中放置错误的参数时,不会发出警告
C++程序员可能会嘲笑我们在这方面遇到的问题:-)正如我所说,直接从活动的onResume调用时,该函数工作正常。查看
getAssignedLocations()
函数可能会有所帮助。请记住,在runnable中调用getAssignedLocations()
时,可能是在主UI线程以外的线程中执行,因此getAssignedLocations()
应该是线程安全函数。我现在将为getAssignedLocations()
添加代码。另外,恐怕我不知道什么是线程安全函数。你能解释一下吗?@Tom你是如何执行你的Runnable
?你的Runnable
是否被发送给绑定到你活动的UI线程(主线程)的处理程序?
/**
* 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;
}