我有一个 TimerTask 导致我的应用程序在我转到不同的 Intent 时崩溃。这是错误:
06-06 02:45:54.884: E/AndroidRuntime(602): FATAL EXCEPTION: main
06-06 02:45:54.884: E/AndroidRuntime(602): android.database.StaleDataException: Access closed cursor
06-06 02:45:54.884: E/AndroidRuntime(602): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:217)
06-06 02:45:54.884: E/AndroidRuntime(602): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
06-06 02:45:54.884: E/AndroidRuntime(602): at com.myapp.ExerciseActivity$TickClass$1.run(ExerciseActivity.java:221)
06-06 02:45:54.884: E/AndroidRuntime(602): at android.os.Handler.handleCallback(Handler.java:587)
06-06 02:45:54.884: E/AndroidRuntime(602): at android.os.Handler.dispatchMessage(Handler.java:92)
06-06 02:45:54.884: E/AndroidRuntime(602): at android.os.Looper.loop(Looper.java:123)
06-06 02:45:54.884: E/AndroidRuntime(602): at android.app.ActivityThread.main(ActivityThread.java:3683)
06-06 02:45:54.884: E/AndroidRuntime(602): at java.lang.reflect.Method.invokeNative(Native Method)
06-06 02:45:54.884: E/AndroidRuntime(602): at java.lang.reflect.Method.invoke(Method.java:507)
06-06 02:45:54.884: E/AndroidRuntime(602): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-06 02:45:54.884: E/AndroidRuntime(602): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-06 02:45:54.884: E/AndroidRuntime(602): at dalvik.system.NativeStart.main(Native Method)
现在这里是 TimerTask 的代码:
public class TickClass extends TimerTask
{
private int columnIndex;
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (cursor != null) {
if (_index == 1) {
columnIndex = cursor.getColumnIndex(MySQLiteHelper.COLUMN_IMAGE_2);
_index = 2;
}
else {
columnIndex = cursor.getColumnIndex(MySQLiteHelper.COLUMN_IMAGE_1);
_index = 1;
}
String image_1 = cursor.getString(columnIndex);
image_1 = image_1.replace(".png", "");
int resourceId = getResources().getIdentifier(getPackageName() + ":drawable/" + image_1, null, null);
image_1_view.setImageDrawable(getResources().getDrawable(resourceId));
}
}
});
}
}
它所做的只是为 PNG 制作动画。
请注意我是如何添加if (cursor != null)
条件语句的,但它并没有修复它。我不知道如何解决这个问题,是不是因为它在 UI 线程上运行,所以即使我已经离开 Activity,它仍在运行,但光标不再存在,因为它与活动?
编辑:
我已经通过取消()TimerTask onPause()来修复强制关闭。但是,现在当我返回 Activity 时,图像不再是动画的。有什么想法吗?