我的应用程序有一个Listview,可以订购一系列讲座。它们根据类型进行颜色编码,我用来执行此操作的自定义适配器由以下代码调用 -
cursor = myDbHelper.getReadableDatabase().rawQuery(sql, null);
startManagingCursor(cursor);
adapter = new Lectures_Adapter(this,R.layout.menu_item,cursor,FROM,TO);
menuList.setAdapter(adapter);
我的自定义适配器中的代码是 -
public class Lectures_Adapter extends SimpleCursorAdapter {
private Context appContext;
private int layout;
private Cursor mycursor;
public Lectures_Adapter(Context context, int layout, Cursor c, String[] from,int[] to) {
super(context, layout, c, from, to);
this.appContext=context;
this.layout=layout;
this.mycursor=c;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = super.getView(position, convertView, parent);
try {
if (position > 0)
{
RelativeLayout rowFill = (RelativeLayout) convertView.findViewById(R.id.rowFill);
String title = mycursor.getString(1);
int myColor = 0;
int myPos = title.indexOf("Nursing");
int myPos2 = title.indexOf("Masterclass");
if (myPos >= 0)
{
myColor = Color.parseColor("#99FF66");
}
else if (myPos2 >= 0)
{
myColor = Color.parseColor("#FF99FF");
}
else
{
myColor = Color.parseColor("#FFFF66");
}
convertView.findViewById(R.id.rowFill).setBackgroundColor(myColor);
}
}catch(Exception e) {
}
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) this.appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(this.layout,null);
} else {
convertView = (View) convertView;
}
return view;
}
}
我有一个按钮,显示一个对话框,提供以四种不同方式重新排序Listview的选项。当他们选择了一个选项时,我使用以下代码重新排序Listview -
Cursor newCursor = myDbHelper.getReadableDatabase().rawQuery(sqlStr, null);
adapter.changeCursor(newCursor);
adapter.notifyDataSetChanged();
这一切似乎都运行正常,除非我重新排序并调用上面的代码,当它运行getView时我收到以下错误'StaleDataException:Access closed cursor'。这是显而易见的,因为光标已关闭,我做错了什么?
答案 0 :(得分:0)
当您使用getCursor()获取当前游标值时,问题就解决了。