我正在使用自定义游标适配器从SQlite视图中获取listview中的类别,并且还希望显示使用相同类别名称保存的特定行数。我尝试多次但不幸地无法成功。
这里是我使用的查询
int GetTasksCountByCategory(String cat)
{
Cursor cur = mDb.rawQuery(" SELECT Count(*) FROM ViewTasks where Category_name = "+"'"+"cat"+"'", null);
int x = 0;
if (cur.moveToFirst())
{
x = cur.getInt(0);
}
cur.close();
return x;
}
和我的Adapter类
public class cursorAdapter2 extends CursorAdapter{
private Context mContext;
DbAdapter myAdapter = new DbAdapter(mContext);
@SuppressWarnings("deprecation")
public cursorAdapter2(Context context, Cursor c) {
super(context, c);
mContext=context;
// TODO Auto-generated constructor stub
}
@Override
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
LayoutInflater inflater = LayoutInflater.from(arg2.getContext());
View retView = inflater.inflate(R.layout.list, arg2, false);
return retView;
}
@SuppressWarnings("unused")
@Override
public void bindView(View view, Context arg1, Cursor cursor) {
// TODO Auto-generated method stub
TextView category = (TextView) view.findViewById(R.id.txtLastcatId);
category.setText(cursor.getString(cursor.getColumnIndex(DbAdapter.KEY_CATEGORY_NAME)));
String getCat = (String) category.getText();
int i = myAdapter.GetTasksCountByCategory(getCat);
Button count = (Button) view.findViewById(R.id.button2);
count.setText(Integer.toString(i));
Button img = (Button) view.findViewById(R.id.button1);
}
}
在这个我得到空指针异常 任何人都帮助我 提前谢谢
答案 0 :(得分:2)
DbAdapter myAdapter
的赋值应该在类'构造函数中完成...当mContext有值时。
public cursorAdapter2(Context context, Cursor c) {
super(context, c);
mContext=context;
myAdapter = new DbAdapter(mContext);
}
其次从....修改查询
Cursor cur = mDb.rawQuery(" SELECT Count(*) FROM ViewTasks where Category_name = "+"'"+"cat"+"'", null);
到
Cursor cur = mDb.rawQuery("SELECT Count(*) FROM ViewTasks where Category_name = ?", new String[] { cat } );
您传递的是字符串"cat"
而不是变量cat
。