Android - Query String instead of integer
I am trying to query a string (TEXT field in the database) and want to fetch records based on that query. I was following a tutorial which works fine if I query an Integer (the _ID field). What will I need to change in the code below to let it search for the string (the TEXT field) instead of the _ID field?
The activity code:
protected void getDetails() {
try
{
// The ArrayList that holds the row data
ArrayList<Object> row;
// ask the database manager to retrieve the row with the given rowID
row = db.getRowAsArray(Long.parseLong(txtProjContacts.getText().toString()));
// update the form fields to hold the retrieved data
txtName.setText((String)row.get(1));
txtEmail.setText((String)row.get(2));
txtExpertise.setText((String)row.get(3));
txtCharges.setText((String)row.get(4));
}
catch (Exception e)
{
Log.e("Retrieve Error", e.toString());
e.printStackTrace();
}
}
The DB Adapter code:
public ArrayList<Object> getRowAsArray(Long rowID)
{
// create an array list to store data from the database row.
// I would recommend creating a JavaBean compliant object
// to store this data instead. That way you can ensure
// data types are correct.
ArrayList<Object> rowArray = new ArrayList<Object>();
Cursor cursor;
try
{
// this is a database call that creates a "cursor" object.
// the cursor object store the information collected from the
// database and is used to iterate through the data.
cursor = db.query
(
TABLE_CONTACTS,
new String[] { TABLE_CON_ID,
TABLE_CON_NAME,
TABLE_CON_EMAIL,
TABLE_CON_EXPERTIS开发者_Go百科E,
TABLE_CON_CHARGES},
TABLE_CON_ID + "=" + rowID,
null, null, null, null, null
);
// move the pointer to position zero in the cursor.
cursor.moveToFirst();
// if there is data available after the cursor's pointer, add
// it to the ArrayList that will be returned by the method.
if (!cursor.isAfterLast())
{
do
{
rowArray.add(cursor.getLong(0));
rowArray.add(cursor.getString(1));
rowArray.add(cursor.getString(2));
rowArray.add(cursor.getString(3));
rowArray.add(cursor.getString(4));
}
while (cursor.moveToNext());
}
// let java know that you are through with the cursor.
cursor.close();
}
catch (SQLException e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
// return the ArrayList containing the given row from the database.
return rowArray;
}
Thanks in advance.
You'll need to make sure you're select condition is such that it's enclosed within quotes.
Untested Code
cursor = db.query
(
TABLE_CONTACTS,
new String[] { TABLE_CON_ID,
TABLE_CON_NAME,
TABLE_CON_EMAIL,
TABLE_CON_EXPERTISE,
TABLE_CON_CHARGES},
TABLE_CON_NAME + "= \"" + name_to_be_searched + "\"",
null, null, null, null, null
);
But this leads to the Possibility of SQL Injection so use SQLLiteQuery
精彩评论