我遇到的问题似乎无法追查其原因。这可能仅仅是因为我对装载机不熟悉......
我有一个自定义适配器,用于在“关闭”位置(单行显示)中为微调器设置提示,直到进行第一次选择。我以前用过这个并取得了很大的成功,但这次它没有用。唯一的区别是现在我正在使用装载机。
当适配器尝试在我重写的getView
方法中访问游标时,游标为空,当然我得到一个强制关闭,空指针异常。我不明白光标在那里是如何为空的,因为显然getDropDownView
方法(我没有覆盖)可以在填充下拉列表时访问光标...
我能想到的是,由于某种原因,getView
方法保留了原始的null,它作为占位符传入,而加载器执行它的工作。我认为当我使用changeCursor
时,引用也会改变,但似乎不是。
主要活动适配器调用
adapter = new CursorAdapter_SpinnerPrompt(this,
R.layout.rowlayout_black, null, new String[] { ThreadMillDB.THREADMILL_THREAD }, new int[] { R.id.ListItem });
mThreadChooser.setAdapter(adapter);
相关的加载程序代码
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.changeCursor(cursor);
}
适配器代码
public class CursorAdapter_SpinnerPrompt extends SimpleCursorAdapter {
private Context context;
private int layout;
private Cursor c;
private String[] from;
private int[] to;
public static boolean spinnerFlag = false;
public CursorAdapter_SpinnerPrompt(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.context = context;
this.layout = layout;
this.c = c;
this.from = from;
this.to = to;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = View.inflate(context, layout, null);
if (spinnerFlag != false) {
c.moveToPosition(position); // cursor is null here... why? How to fix?
TextView tv = (TextView) convertView;
tv.setText(c.getString(c.getColumnIndex(ThreadMillDB.THREADMILL_THREAD)));
} else {
TextView tv = (TextView) convertView;
tv.setText("Choose a thread");
tv.setTextColor(Color.parseColor("#778899"));
}
return convertView;
}
}
更新
当然,在输入时,我想出了一个解决方案。我将适配器的创建从我的活动onCreate
移到了onLoadFinished
并将光标放入了调用中。然而,这似乎比我试图做的方式更加混乱。我可以对我的原始方法(如上所示)进行任何修改,使其无需将适配器实例移动到onLoadFinished
方法即可工作吗?
答案 0 :(得分:1)
你的可疑是正确的。
您在构造函数中记住的游标引用与您在chageCursor(Cursor c)
上传递的游标引用不同。
将光标放在CursorAdapter上的正确方法是调用getCursor()
,而不是获得对changeCursor(Cursor c)
传递的光标的引用。