0

我正在使用自定义光标适配器从 SQlite 视图中获取列表视图中的类别,并且还希望显示使用相同类别名称保存的特定行数。我尝试了很多次,但不幸的是无法成功。

这里是我使用的查询

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;    
 }

和我的适配器类

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);
    }

}

在这我得到空指针异常任何人请提前帮助我thanx

4

1 回答 1

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

于 2013-02-18T14:01:49.027 回答