SQL cursor error
I have been using the notepad SQLhelper (notesDBadapter) as a model, some of it works, some doesn't. I can get a cursor for 'fetchallrecords() but it crashes if I try a call passing an argument and using the 'WHERE'. The argument is passed but the cursor fails. My code in activity;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listselectedfile);
//Button ID clicked in previous activity
Bundle bundle = getIntent().开发者_开发技巧getExtras();
int BtnId = bundle.getInt("ButtonID");
Toast.makeText(this, "ButtonID selected in Main:= " + BtnId, Toast.LENGTH_LONG) .show();
mDbHelper = new SectionsDbAdapter(this);
mDbHelper.open();
fillData();
}
private void fillData() {
// Get all of the notes from the database and create the item list
//Cursor c = mDbHelper.fetchAllRecords(); <=== works fine
Cursor c = mDbHelper.fetchRecordsbySource("UK"); <=== fails in DBhelper
startManagingCursor(c);
String[] from = new String[] { SectionsDbAdapter.KEY_DESC };
//String[] from = new String[] { SectionsDbAdapter.KEY_SOURCE }; <=== can fetch this column from table
int[] to = new int[] { R.id.tv_full_width }; //the R.id.xxx= view in the .xml file
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter records =
new SimpleCursorAdapter(this, R.layout.section_row_full_width, c, from, to); //the .xml file containing the R.id.xxxx
setListAdapter(records);
}
In the DBhelper; This call works and returns the full table;
public Cursor fetchAllRecords() {
return mDb.query(DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_DESC, KEY_DEPTH, KEY_TWEB,
KEY_BF1, KEY_TF1, KEY_BF2, KEY_TF2,
KEY_IMAJOR, KEY_IMINOR,
KEY_PLMAJOR, KEY_PLMINOR,
KEY_JTORSION, KEY_AREA,
KEY_WARPING, KEY_CYCHANNEL,
KEY_SHAPE, KEY_SOURCE,
KEY_UNITS},null, null, null, null, null);
}
This call fails on the cursor (the argument is passed successfully);
public Cursor fetchRecordsbySource(String source) throws SQLException {
Log.v("In fetchRecordsbySource", "source = " +source);
Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_DESC}, KEY_SOURCE + " = " + source, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
There is nothing obvious to me in the Eclipse debug, but, as a newby, I probably have not got the necessary perspective.
Can anyone spot the error?
In the code you have, if source is a non-numeric value, it needs to surrounded by single quotes, like this:
KEY_ROWID, KEY_DESC}, KEY_SOURCE + " = '" + source + "'", null, null, null, null, null)
But you will be better off if you pass your filter arguments as ?; this avoids (among other things) SQL injection attacks
KEY_ROWID, KEY_DESC}, KEY_SOURCE + " = ?", new String[] { source }, null, null, null, null)
精彩评论