Android getting value of db key of sql - android

I'm trying to get the value in a specific column in my database and here's the code I have as of now to achieve it:
String id = db.KEY_ID;
but all I get now is the title of of the column, which in this case, id, instead of the value itself, such as 1, 2, etc. How do I grab the value and not the key of a database? Thanks!!!

You need to create a query statement and execute it against the data base. You use db.KEY_ID to specify in the query what column of data you want.

A simple example:
public String getEntry(long rowIndex){
String value = "";
Cursor c = db.query(DATABASE_TABLE, new String[] {KEY_NAME, VALUE}, KEY_NAME + "=" + rowIndex, null, null, null, null);
int columnIndex = c.getColumnIndex(VALUE);
int rowsCount = c.getCount();
if(rowsCount > 0){
String value = c.getString(columnIndex);
}
return value;
}

Related

Can't extract integer from cursor after preforming sqlite query in Android

I'm working on an small android app that maintains a small database of tools which I lend out to other people.
As part of the app, I am incorporating an sqllite database, where I am having a bit of trouble performing queries and working with cursors once the queries have been executed.
The code in question is as follows:
String COLUMN_NAME = "toolName";
String[] columns = { COLUMN_NAME };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = {tool};
Cursor cursor = mToolDb.query(ToolStatisticContract.ToolStatisticEntry.TABLE_NAME, columns,
selection, selectionArgs, null, null, null, null);
return Integer.parseInt(cursor.getString(3));
The contract for the database is as follows:
public class ToolStatisticContract {
public static final class ToolStatisticEntry implements BaseColumns {
public static final String TABLE_NAME = "tooltable";
public static final String COLUMN_TOOL_NAME = "toolName";
public static final String COLUMN_LIFESPAN = "lifespan";
public static final String COLUMN_USAGE = "usageTime";
}
}
I am essentially trying to extract out the value from COLUMN_USAGE, which seems to be producing errors with regards to parsing the value to an integer. The value in the COLUMN is actually an integer typecasted as a String from a previous segment of code, so I'm fairly certain the error is encompasssed with the code snippets above.
Thanks again in advance for all your help!
The code in question is as follows
The net SQL statement is something like:
SELECT toolName FROM tooltable WHERE toolName = ?
And there is no column with index 3, since you are only returning 1 column.
You need to:
Have usageTime in your column list (COLUMNS)
Move the Cursor to a valid row (as it initially is positioned before the first row)
Pass getInteger() the value that lines up with COLUMNS to retrieve usageTime
You could use the following. This uses null instead of columns, which will get all columns (i.e. resolves to SELECT * FROM table). It checks that a row has been returned and only then does it try to get the data. It also closes the cursor (you should close a cursor when done with it). It uses cursor.getInt() to get the integer value rather than convert it from a string to int. It assumes that you'll only get 1 row (if no rows then 0 will be returned).
int returnvalue = 0;
String COLUMN_NAME = "toolName";
String[] columns = { COLUMN_NAME };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = {tool};
Cursor cursor = mToolDb.query(ToolStatisticContract.ToolStatisticEntry.TABLE_NAME, null,
selection, selectionArgs, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
returnvalue = cursor.getInt(2);
//or returnvalue = Integer.parseInt(cursor.getString(2));
}
cursor.close();
return returnvalue;
Note! I haven't checked this just coded it from memory, so apologies for the odd mistake.
To do the above using specific columns then you could use:-
String COLUMN_NAME = "toolName";
String[] columns = { COLUMN_USAGE };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = {tool};
Cursor cursor = mToolDb.query(ToolStatisticContract.ToolStatisticEntry.TABLE_NAME, columns,
selection, selectionArgs, null, null, null, null);
In which case the column index would be 0 (that is the index is according to the column's in the cursor). However it might be better to use, the following which gets the column index according to the column's name:-
cursor.getInt(cursor.getColumnIndex(COLUMN_USAGE);
The easiest way to read a single value from the database is to use a helper function that allows you to avoid having to handle cursor objects:
String query = "SELECT usageTime FROM tooltable WHERE toolName = ?";
String[] selectionArgs = { tool };
long returnvalue = DatabaseUtils.longForQuery(mToolDb, query, selectionArgs);

SQLite DB select method with different types in where clause

I have the following code that works and gets a record from a database.
public Audit getAudit(SQLiteDatabase db, String projectId, String date,String type, int category) {
String[] columns = { "user_id", "submitted", "answers" };
String[] whereArgs = new String[]{projectId, date, type};
Cursor c = db.query("AUDITS", columns, "project_id = ? AND date = ? AND type = ?",whereArgs, null, null, null);
if (c != null)
{
Audit audit = new Audit(projectId, type, category, c.getString(c.getColumnIndex("user_id")), date, c.getInt(c.getColumnIndex("submitted")), c.getString(c.getColumnIndex("user_id")));
return audit;
}
return null;
}
But now I want to add another column to the Where clause, and this column holds an integer and not a string. So I can not add it to whereArgs array which holds strings. Is there a way that I can still use this method with mixing types or do I need to just do a raw query??
The Integer.toString() way seems to be best as "the values will be bound as Strings" in the query method. See the answer to
Android SQLite query with integer parameter

ERROR : CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

Hy Guys, I am Beginner Android Developer. I need your help. i want to insert data into 2 tables of sqlite tblorder, and orderdtl. on orderdtl i have to insert data from multiple item from listview. i try to toast all variable that i want to inserted. their all appears. but when i try to save it. i get those error.
this is my DBDataSource.java
public order createorder(String orderid, String notes, long outletid) {
ContentValues values = new ContentValues();
values.put(DBHelper.ORDER_ID, orderid); // inserting a string
values.put(DBHelper.NOTES, notes); // inserting an int
values.put(DBHelper.OUTLET_ID, outletid); // inserting an int
long insertId = database.insert(DBHelper.TABLE_ORDER, null,
values);
Cursor cursor = database.query(DBHelper.TABLE_ORDER,
allorder, DBHelper.ORDER_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
order neworder = cursorToorder(cursor);
cursor.close();
return neworder;}
private order cursorToorder(Cursor cursor) {
order order = new order();
order.setorderid(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_ID)));
order.setorderdate(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_DATE)));
order.setnotes(cursor.getString(cursor.getColumnIndex(DBHelper.NOTES)));
order.setoutletid(cursor.getLong(cursor.getColumnIndex(DBHelper.OUTLET_ID)));
return order;
}
The error refer to this code
Cursor cursor = database.query(DBHelper.TABLE_ORDER,
allorder, DBHelper.ORDER_ID + " = " + insertId, null,
null, null, null);
And this code
order.setorderid(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_ID)));
orderid is string, i try to get from yyyyMMddHHmmss.this is the code:
private String orderid(){
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyyMMddHHmmss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
I would be very grateful for any help that you give.Thank You.
The query didn't match any rows. Check the result of moveToFirst() to see whether the operation succeeded and only then access cursor data.
Example:
order neworder = null;
if (cursor.moveToFirst()) {
order neworder = cursorToorder(cursor);
}
cursor.close();
return neworder;
The insertId you get from insert() is the sqlite row id for the row. It's likely not the same as ORDER_ID. To make a column an alias for rowid, declare it as INTEGER PRIMARY KEY.
The error I see in logcat is not about _Player_8, but about the unknown column "KEY_Team_Name"
The problem is in your activity, the line prior to the last one:
String EntryA =String.valueOf( db.getentry("Ravirrrr", "KEY_Team_Name"));
It should be:
String EntryA =String.valueOf( db.getentry("Ravirrrr", DatabaseHandler.KEY_Team_Name));
And the DatabaseHandler should have all column names public, as the getentry method requires a column name.
Edit: adding an answer to the question in the comments below.
After calling db.query, you should check if you got something by calling Cursor.isAfterLast(). If true, the select returned an empty result set.
In your example, you WILL get an empty result set as the code creates an entry with "Ravi" as the team name, then asks for a team named "Ravirrrr".

how to retrieve a specific string data from sqlite database by using 2 string arguments?

this is my code used which i use for making method
String item = item1.getText().toString();
item = item.toLowerCase();
String date = getDate();
edited = new Datahelper(this);
edited.open();
String returnedprice = edited.getprice(item,date);
String returneddetail = edited.getdetail(item,date);
edited.close();
price.setText(returnedprice);
details.setText(returneddetail);
and this is my code of method that i am using for getting that string but here i dont know how to use the 2nd date string so that the string price that return is from a row that contains that item and that date.. please give me the code of how to do it..
public String getprice(String item ,String date) {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID,
KEY_CATEGORY,KEY_DATE,KEY_PRICE,KEY_DETAILS};
Cursor v =ourDatabase.query(DATABASE_TABLE, columns, KEY_CATEGORY + " ='" + item
+"'",null,null, null, null);
if(v!=null){
String price = v.getString(3);
return price;
}
return null;
}
public String getdetail(String item,String date) {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID,
KEY_CATEGORY,KEY_DATE,KEY_PRICE,KEY_DETAILS};
Cursor v =ourDatabase.query(DATABASE_TABLE, columns, KEY_CATEGORY + " ='" + item +
"'",null,null, null, null);
if(v!=null){
String detail = v.getString(4);
return detail;
}
return null;
}
So probably you want to use two arguments in select query so:
You can use two methods:
rawQuery()
query()
I will give you basic example for both cases.
First:
String query = "select * from Table where someColumn = ? and someDateColumn = ?";
Cursor c = db.rawQuery(query, new String[] {textValue, dateValue});
Explanation:
So i recommend to you use ? that is called placeholder.
Each placeholder in select statement will be replaced(in same order so first placeholder will be replaced by first value in array etc.) by values from selectionArgs - it's String array declared above.
Second:
rawQuery() method was easier to understand so i started with its. Query() method is more complex and has a little bit more arguments. So
columns: represents array of columns will be selected.
selection: is in other words where clause so if your selection is
KEY_COL + " = ?" it means "where " + KEY_COL + " = ?"
selectionArgs: each placeholder will be replaced with value from this
array.
groupBy: it's multi-row (grouping) function. more
about
having: this clause is always used with group by clause here is
explanation
orderBy: is clause used for sorting rows based on one or multiple
columns
Also method has more arguments but now you don't need to care about them. If you will, Google will be your friend.
So let's back to explanation and example:
String[] columns = {KEY_COL1, KEY_COL2};
String whereClause = KEY_CATEGORY " = ? and " + KEY_DATE + " = ?";
String[] whereArgs = {"data1", "data2"};
Cursor c = db.query("Table", columns, whereClause, whereArgs, null, null, null);
So whereClause contains two arguments with placeholder for each. So first placeholder will be replaced with "data1" and second with "data2".
When query is performed, query will look like:
SELECT col1, col2 FROM Table WHERE category = 'data1' AND date = 'data2'
Note: I recommend to you have look at Android SQLite Database and ContentProvider - Tutorial.
Also i recommend to you an usage of placeholders which provide safer and much more readable and clear solutions.
You should read any SQL tutorial to find out what a WHERE clause it and how to write it.
In Android, the selection parameter is the expression in the WHERE clause.
Your query could be written like this:
c = db.query(DATABASE_TABLE, columns,
KEY_CATEGORY + " = ? AND " + KEY_DATE + " = ?",
new String[] { item, date },
null, null, null);

No result on sqlite query

Hi all
I create a table like that
private static final String CREATE_TABLE_PRODUCT =
"create table prod (id integer primary key,titre text not null, desc text, is_free integer);";
i update it this way
SQLiteDatabase db = getConnection();
ContentValues updateEvent = new ContentValues();
updateEvent.put("is_free", 1);
int ok = db.update(prod, updateEvent, "id=?",
new String[] { Long.toString(evenement.getId()) });
db.close();
I do see the change in eclipse with DDMS questoid
but when i try to retrieve the value I get nothing ....
Cursor c = db.query(prod, new String[] { "id",
"titre", "desc", "is_free", },
"is_free=?", new String[] {"1"}, null, null,
null);
I've tried some variant like
String query = "SELECT * FROM "+EVENEMENT_TABLE+" WHERE is_free=1;";
Cursor c = sdb.rawQuery(query, null);
with no success
is this problem come from the type (integer) of my column ?
Any help
Do not use reserved keywords like desc in your queries. This probably causes query to fail.
In case you don't know update will not add values to the table. Use insert instead.

Categories

Resources