我是android编程的新手,所以请帮助我: 我需要获取特定记录的计数,这是我的代码:
public int countFiltered(String selection){
Cursor cursor = database.query(DenverDBOpenHelper.TABLE_DENVERS, denverAllColumns, selection, null, null, null, null);
Log.i(LOGTAG, "Get " + cursor.getCount() + " rows");
int countItem = cursor.getCount();
if(cursor==null) {
return 0;
}else
return countItem;
}
我将其称为另一项活动:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_baby, container, false);
txtPass = (TextView)rootView.findViewById(R.id.txtPass);
int countPass = dataSource.countFiltered("score == 1");
txtPass.setText(countPass);}
countPass显示NullPinterException
我的得分列类型是INTEGER,这是我的DBOpenHelper:
public class DenverDBOpenHelper extends SQLiteOpenHelper {
private static final String LOGTAG = "LitleDenver";
private static final String DATABASE_NAME = "db_denver";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_DENVERS = "denvers";
public static final String COLUMN_ID = "itemId";
public static final String COLUMN_CATEGORY = "category";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_DESC = "description";
public static final String COLUMN_DETAIL = "detail";
public static final String COLUMN_IMAGE = "image";
public static final String COLUMN_MIN = "min";
public static final String COLUMN_MAX = "max";
public static final String COLUMN_SCORE = "score";
public static final String COLUMN_STATUS = "status";
private static final String TABLE_CREATE =
"CREATE TABLE " + TABLE_DENVERS + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_CATEGORY + " TEXT, " +
COLUMN_TITLE + " TEXT, " +
COLUMN_DESC + " TEXT, " +
COLUMN_DETAIL + " TEXT, " +
COLUMN_IMAGE + " TEXT, " +
COLUMN_MIN + " INTEGER, " +
COLUMN_MAX + " INTEGER, " +
COLUMN_SCORE + " INTEGER, " +
COLUMN_STATUS + " INTEGER " +
")";
答案 0 :(得分:1)
您将希望使用query
,其中selectionArgs(您有null)作为您要查找的值的String数组(想想where子句)。此外,我通过在空游标上调用getCount()
来清除代码,以便在游标为空的情况下不会导致NPE
public int countFiltered(String selection, String argValue){
String selectionArg = new String[] { argValue };
Cursor cursor = database.query(DenverDBOpenHelper.TABLE_DENVERS,
denverAllColumns,
selection,
selectionArg,
null, null, null);
if(cursor==null) {
return 0;
} else {
return cursor.getCount();
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_baby, container, false);
txtPass = (TextView)rootView.findViewById(R.id.txtPass);
int countPass = dataSource.countFiltered("score = ?", "1");
Log.i(LOGTAG, "Get countPass = " + countPass);
txtPass.setText(countPass);
}
答案 1 :(得分:0)
尝试修改第二行到最后一行,如下所示:
int countPass = dataSource.countFiltered("['score'] = 1");
我有一个非常类似的问题,这是我的修复。
答案 2 :(得分:0)
您需要发布更多信息,作为字段的名称,类的可见性,这将返回您的logcat。