how to get a specific data by using a string argument? - android

i am using this method to get the price of all item that has a category name value bt it is not showing anything...
public long getcostmain(String xyz)throws SQLException {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_CATEGORY,KEY_DATE,KEY_PRICE,KEY_DETAILS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_DATE + "=" + xyz, null, null, null, null);
long cost = 0;
for(c.moveToFirst(); ! c.isAfterLast(); c.moveToNext()){
cost = cost + c.getLong(3);
}
return cost;
}

In your code, when you query data from your database, you need to change your code to following:
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_DATE + "='" + xyz +"'", null, null, null, null);
You need to put ' mark around your xyz string.

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

updating or inserting in a table with keeping the row numbers to one

I am trying to see if there is something in my table update it and if not insert one row. So basically I will have one row always in my table.
public void createOrupdate(long id,String x, String y, String angle){
String[] columns= new String[]{KEY_ROWID, KEY_X, KEY_Y, KEY_ANGLE};
Cursor c= ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
ContentValues editCon = new ContentValues();
if (c!=null){
editCon.put(KEY_X, x);
editCon.put(KEY_Y, y);
editCon.put(KEY_ANGLE, angle);
ourDatabase.update(DATABASE_TABLE, editCon, KEY_ROWID + "=?", new String[]{String.valueOf(id)});
}
else{
editCon.put(KEY_X, x);
editCon.put(KEY_Y, y);
editCon.put(KEY_ANGLE, angle);
ourDatabase.insert(DATABASE_TABLE, null, editCon);
}
}
public String getData() {
// TODO Auto-generated method stub
String[] columns= new String[]{KEY_ROWID, KEY_X, KEY_Y, KEY_ANGLE};
Cursor c= ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result= "";
int iRow= c.getColumnIndex(KEY_ROWID);
int iX= c.getColumnIndex(KEY_X);
int iY= c.getColumnIndex(KEY_Y);
int iAngle= c.getColumnIndex(KEY_ANGLE);
int i= 0;
for( c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result= result+ c.getString(iRow)+ " "+ c.getString(iX)+ " " +c.getString(iY)+ " "+ c.getString(iAngle)+"\n";
}
return result;
}
But when I use entry.createOrupdate(1, Double.toString(db1), Double.toString(db2), Double.toString(db3)); in my code there is nothing in my table and no exception and nothing. when i use update or insert separately it works.. what is the problem?
The check for c!=null is not enough. The cursor can be not null even when the result of the query was empty. That means you need to get the amount of rows by using c.getCount() and check if that returns 0 or 1.
PS: This for( c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){ is a pretty ugly use for a loop. You should change that to something like while(c.moveToNext()).
moveToNext() will be the same like moveToFirst() on a fresh created cursor object.

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.

SQLiteDatabase - How to use where clause?

public Cursor fetchTimetable() {
return mDb.query(DATABASE_TABLE_TIMETABLE, new String[] {TIMETABLE_ROWID, TIMETABLE_MODULECODE, TIMETABLE_MODULENAME, TIMETABLE_ROOM, TIMETABLE_LECTURER, TIMETABLE_TIME}, null, null, null, null, null);
}
For example if i wanted TIMETABLE_MODULECODE = 123. How would i do this, i have read its the first null. I have tried this below but still doesnt work
public Cursor fetchTimetable() {
String a = "TIMETABLE_CODE = ADD";
return mDb.query(DATABASE_TABLE_TIMETABLE, new String[] {TIMETABLE_ROWID, TIMETABLE_MODULECODE, TIMETABLE_MODULENAME, TIMETABLE_ROOM, TIMETABLE_LECTURER, TIMETABLE_TIME}, a, null, null, null, null);
}
My working example with where args (it's more clear with using it):
String [] settingsProjection = {
DBContract.Settings._ID,
DBContract.Settings.COLUMN_NAME_USER_ID,
DBContract.Settings.COLUMN_NAME_AUTO_LOGIN
};
String whereClause = DBContract.Settings.COLUMN_NAME_USER_ID+"=?";
String [] whereArgs = {userId.toString()};
Cursor c = db.query(
DBContract.Settings.TABLE_NAME,
settingsProjection,
whereClause,
whereArgs,
null,
null,
null
);
db.query
(
TABLE_NAME,
new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO },
TABLE_ROW_ID + "=" + rowID,
null, null, null, null, null
);
TABLE_ROW_ID + "=" + rowID, here "=" is the where clause
What exactly does "still doesn't work" mean?
The following code should work just fine:
public Cursor fetchTimetable() {
String[] columnNames = new String[] {TIMETABLE_ROWID, TIMETABLE_MODULECODE, TIMETABLE_MODULENAME, TIMETABLE_ROOM, TIMETABLE_LECTURER, TIMETABLE_TIME};
String whereClause = "TIMETABLE_MODULECODE=123";
return mDb.query(DATABASE_TABLE_TIMETABLE, columnNames, whereClause, null, null, null, null);
}
the right syntax is
String[] projection= {column names};
String[] where={"values for where clause"}; //this must be array
public Cursor fetchTimetable() {
return mDb.query(TABLE_NAME, projrction, "columname"+"=?", where, null, null, null);
}
The simple way:
return mDb.rawQuery("SELECT * FROM myTable WHERE column1 = "+ someValue, null);
You can use Use this query:
SQLiteDatabase db = this.getReadableDatabase();
//Cursor cursorr = db.rawQuery(Query, null);
Cursor cursorr = db.rawQuery("select * from " + DATABASE_TABLE_EHS + " where " + TASK_ID + "='" + taskid + "'" , null);
if (cursorr.moveToFirst())
{
do {
// your code like get columns
}
while (cursorr.moveToNext());
}
}
If you're checking against a string value you'll want to wrap the string in quotes like below:
dbHelper.COL_EMAIL +"='"+givenEmail+"'",

Categories

Resources