How do i query SQLite table by string? - android

I'm a noob to android and im am trying to query a sqlite table. I have read several tutorials and know how to query a table to return an entire column of values, but i can't seem to figure out how to query a just a single value from a column by string. Any help is greatly appreciated. here is my code:
My successful code to query and return values for entire column:
public String getValue() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_OUNCES, KEY_VALUE };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iQuantity = c.getColumnIndex(KEY_QUANTITY);
int iOunces = c.getColumnIndex(KEY_OUNCES);
int iValue = c.getColumnIndex(KEY_VALUE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + /*c.getString(iRow) + " " +*/ c.getString(iValue) + "\n";
}
return result;
}
My attempt to query column for single value by string:
public String getSingleValue(String aCoin) throws SQLException{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_OUNCES, KEY_VALUE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + aCoin, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iQuantity = c.getColumnIndex(KEY_QUANTITY);
int iOunces = c.getColumnIndex(KEY_OUNCES);
int iValue = c.getColumnIndex(KEY_VALUE);
if (c != null){
c.moveToFirst();
result= c.getString(1);
return result;
}
return null;
}

Change this
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_OUNCES, KEY_VALUE };
to
String[] columns = new String[]{ KEY_NAME};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + aCoin, null, null, null, null);
String result = "";
if (c != null){
c.moveToFirst();
result= c.getString(0);
return result;
}
return null;
If you want to only get the name column.

Related

Get specific data from sqlitedatabase using row id

I have two columns in a database, id and city. How can I get all the city data and put it in a string when the row id is less than 3. I am having difficulty in writing a query to get data when the row id is less than 3. Right now my method gets all the data from the database. Thanks.
String[] columns = new String[]{KEY_ROWID, KEY_CITY};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result =" ";
int iRow = c.getColumnIndex(KEY_ROWID);
int iCity = c.getColumnIndex(KEY_CITY);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iCity) + "\n";
}
return result;
String[] columns = new String[]{KEY_ROWID, KEY_CITY};
// "note "rowid" is used in fts tables and "id" in normal tables.
// I'm assuming your constant KEY_ROWID chose the correct one.
String where = KEY_ROWID + " <= " + 3;
Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, where, null, null, null, null);
if(!cursor.moveToFirst()){
Log.e("System.out", "cursor is empty");
}else{
int ix_city = cursor.getColumnIndexOrThrow(KEY_CITY);
StringBuilder sb = new StringBuilder();
do{
String city = cursor.getString(ix_city);
Log.i("System.out", "city name " + city);
if(TextUtils.isEmpty(city))
continue;
sb.append(city).append("\n");
}while(cursor.moveToNext());
Log.i("System.out", "the entire list " + sb.toString());
}

Cannot retrieve List<String> from an SQLIte query method

In my android project ,I have successfully created an SQLite Database , Insertion operations are also successful.
I cannot retrieve the List into a method .
here is my calling method:
protected void getTheServerList() {
ServerManger info = new ServerManger(this);
try {
info.open();
servers = info.getData();
info.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "EXCEPTION !",
Toast.LENGTH_SHORT).show();
} finally {
}
}
and here is my SQLIte method
public List<String > getData() {
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_UNAME,
KEY_PASSWORD };
List<String> sItems=null;
Cursor c = ourDatabase.query(TABLE_NAME, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iUname = c.getColumnIndex(KEY_UNAME);
int iPass = c.getColumnIndex(KEY_PASSWORD);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
//sItems.add(KEY_NAME);
result =c.getString(iName);
sItems.add(result);
}
c.close();
return sItems;
}
and I get an Exception
03-12 12:19:15.798: E/Database(390): close() was never explicitly called on database '/data/data/com.example.proj/databases/PROJ_DB'
I can retrieve the String , but not the- List
Please help !
public List<String > getData() {
String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_UNAME,
KEY_PASSWORD };
List<String> sItems=new ArrayList<String> // define instance Here you create listview but not creat this instance
Cursor c = ourDatabase.query(TABLE_NAME, columns, null, null, null,
null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iUname = c.getColumnIndex(KEY_UNAME);
int iPass = c.getColumnIndex(KEY_PASSWORD);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
//sItems.add(KEY_NAME);
result =c.getString(iName);
sItems.add(result);
}
c.close();
return sItems;
}
initiate your list.. list is null
List<String> sItems=new ArrayList<String>();

querying sqlite using string as where condition

why does when i use a string as a where condition in my database, my program just force close. though it is working fine if i use number as a query condition. please help me, thanks
public ArrayList<Contact> getAvailableList()
{
// TODO Auto-generated method stub
ArrayList<Contact> results = new ArrayList<Contact>();
String[] columns = new String[]{KEY_NAME, KEY_NUMBER, KEY_STATUS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_STATUS +"=available" , null, null, null, KEY_NAME);
String sName = "";
String sNum = "";
String status = "";
int iName = c.getColumnIndex(KEY_NAME);
int iNumber = c.getColumnIndex(KEY_NUMBER);
int iStatus = c.getColumnIndex(KEY_STATUS);
Contact contact;
for(c.moveToFirst(); ! c.isAfterLast(); c.moveToNext())
{
contact = new Contact();
sName += c.getString(iName);
sNum += c.getString(iNumber);
status += c.getString(iStatus);
contact.setName(sName);
//contact.setPhoneNumber(sNum);
contact.setPhoneNumber("0".concat(sNum));
contact.setStatus(status);
results.add(contact);
sName = "";
sNum = "";
status = "";
}
return results;
}
You need to wrap strings in SQL with quotes, like this:
// Add these v v
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_STATUS +"='available'",
null, null, null, KEY_NAME);
Or if you want to use dynamic data, you should use the selectionArgs parameter:
String status = "available";
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_STATUS +"=?",
new String[] {status}, null, null, KEY_NAME);
This approach simplifies keeping track of matching quotes in complex Java/SQL Strings, more importantly it protect you from SQL injections.
You forgot ' ' around available
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_STATUS +"='available'" , null, null, null, KEY_NAME);

Is it possible to set column width in SQLite table?

I am trying to display a SQLite table in a view. I want my first column to have a width of 20 characters. I have attempted to achieve this effect by using the substring method but I get stringindexoutofboundsexceptions with strings less than 20 characters. Any help is greatly appreciated. Here is my code:
Method for displaying table in view:
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_VALUE };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iQuantity = c.getColumnIndex(KEY_QUANTITY);
int iValue = c.getColumnIndex(KEY_VALUE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + /*c.getString(iRow) + " " +*/ c.getString(iName).substring(0, 20) + " " + c.getString(iQuantity) + " " + c.getString(iValue) + "\n";
}
Just use c.getString(iName).substring(0, Math.min(20, c.getString(iName).length()) (possibly using a temporary for c.getString(iName)) instead of the substring you have now.
If you don't want them then why select. You can just do
String[] columns = new String[]{ KEY_ROWID, "substr(" + KEY_NAME + ",1,20)", KEY_QUANTITY, KEY_VALUE };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
and get at most 20 chars from the column.

Trying a query using an int and a string

I am not having a lot of luck figuring out how to query with an int and a string. I have found examples with two ints and I have found examples with two strings. I have tried different combinations and nothing seems to work. Below are two examples of what I have tried and have not worked. What am I doing wrong. I have used both inpspection_id and item_name on there own and they both work.
Try 1:
public int getId(int inspection_id ,String item_name)throws Exception
{
Cursor c = db.query(DB_TABLE, new String[] {KEY_INSPECTION_ID, KEY_ITEM_NAME},
"inspection_id=" + inspection_id +"item_name='"+ item_name + "'", null, null, null, null);
int id=c.getColumnIndex(KEY_ROWID);
c.moveToFirst();
String result=c.getString(id);
int primId=Integer.parseInt(result);
c.close();
return primId;
}
Try 2:
public int getId(int inspection_id ,String item_name)throws Exception
{
Cursor c = db.query(DB_TABLE, new String[] {KEY_INSPECTION_ID, KEY_ITEM_NAME},
"inspection_id=" + inspection_id +"AND KEY_ITEM_NAME = ?", new String[]{item_name}, null, null, null);
int id=c.getColumnIndex(KEY_ROWID);
c.moveToFirst();
String result=c.getString(id);
int primId=Integer.parseInt(result);
c.close();
return primId;
}
Try 3:
public int getId(int inspection_id ,String item_name)throws Exception
{
String s_id= Integer.toString(inspection_id);
Cursor c = db.query(DB_TABLE, new String[] {KEY_INSPECTION_ID, KEY_ITEM_NAME},
"KEY_INSPECTION_ID = ? AND KEY_ITEM_NAME = ?",
new String[] { s_id, item_name }, null, null, null);
int id=c.getColumnIndex(KEY_ROWID);
c.moveToFirst();
String result=c.getString(id);
int primId=Integer.parseInt(result);
c.close();
return primId;
}
try it this way, with single quotes for the int ones.
"inspection_id='" + inspection_id +"'item_name='"+ item_name + "'"

Categories

Resources