How to get specific value from DB by id - android

How to get specific value from DB by id.
This is my table: TABLE-RECORDS-(name of table) and KEY-ID , KEY-PRICE ... I'm trying to get KEY-PRICE by KEY-ID and can not. How to do it?

I don't know if this is exactly what you are looking for, but this is the query.
SELECT key-price FROM table-record WHERE key-id='id number you need';

// please change the column names of database if i have mistaken
public Cursor getCursor(int id) {
SQLiteDatabase db = this.getReadableDatabase();
String from[] = {"key-price"};//this is the edit1
String where = "key-id=?";//this is the edit2
String[] whereArgs = new String[]{String.valueOf(id)+""}; //this is the edit3
Cursor cursor = db.query(true, table-records, from, where, whereArgs, null, null, null, null);
return cursor;
}
//just call this function and see the magic
private int getPrice(int id) {
Cursor c = getCursor(id);
int price=-1;
if(c != null)
{
while(c.moveToNext){
//assuming price is an integer
price = c.getInt(0);//edit 4
// use these strings as you want
}
}
return price;
}

Related

How to write a sqlite query to get specific data?

I want to get the first name, middle name and last name of a student whose userid is used for login. I have written this particular piece of code but it stops my application.
I have used both the ways like database.query() and .rawquery() also.
Cursor studentData(String userId) {
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(studentTable, new String[] { "First_Name", "Middle_Name", "Last_Name"}, "User_ID=?", new String[] { userId }, null, null, null, null);
// Cursor cursor = db.rawQuery("select First_Name, Middle_Name, Last_Name from Student_Table where User_ID =?", new String[]{userId});
String data = cursor.getString(cursor.getColumnIndex("First_Name"));
db.close();
return cursor;
}
I should get whole name in the string.
You have a number of issues.
Attempting to use String data = cursor.getString(cursor.getColumnIndex("First_Name"));,
will result in an error because you have not moved the cursor beyond BEFORE THE FIRST ROW and the attempt to access the row -1 will result in an exception (the likely issue you have encountered).
you can use various move??? methods e.g. moveToFirst, moveToNext (the 2 most common), moveToLast, moveToPosition.
Most of the Cursor move??? methods return true if the move could be made, else false.
You CANNOT close the database and then access the Cursor (this would happen if the issue above was resolved)
The Cursor buffers rows and then ONLY when required.
That is The Cursor is when returned from the query method (or rawQuery) at a position of BEFORE THE FIRST ROW (-1), it's only when an attempt is made to move through the Cursor that the CursorWindow (the buffer) is filled (getCount() included) and the actual data obtained. So the database MUST be open.
If you want a single String, the full name, then you could use :-
String studentData(String userId) { //<<<<<<<<<< returns the string rather than the Cursor
SQLiteDatabase db = getWritableDatabase();
String rv = "NO NAME FOUND"; //<<<<<<<<<< value returned if no row is located
Cursor cursor = db.query(studentTable, new String[] { "First_Name", "Middle_Name", "Last_Name"}, "User_ID=?", new String[] { userId }, null, null, null, null);
if (cursor.modeToFirst()) {
String rv =
cursor.getString(cursor.getColumnIndex("First_Name")) +
" " +
cursor.getString(cursor.getColumnIndex("Middle_Name")) +
" " +
cursor.getString(cursor.getColumnIndex("Last_Name"));
}
cursor.close(); //<<<<<<<<<< should close all cursors when done with them
db.close(); //<<<<<<<<<< not required but would result in an exception if returning a Cursor
return rv;
}
Or alternately :-
String studentData(String userId) { //<<<<<<<<<< returns the string rather than the Cursor
SQLiteDatabase db = getWritableDatabase();
String rv = "NO NAME FOUND"; //<<<<<<<<<< value returned if no row is located
Cursor cursor = db.query(studentTable, new String[] { "First_Name"||" "||"Middle_Name"||" "||"Last_Name" AS fullname}, "User_ID=?", new String[] { userId }, null, null, null, null);
if (cursor.modeToFirst()) {
String rv =
cursor.getString(cursor.getColumnIndex("fullname"));
}
cursor.close(); //<<<<<<<<<< should close all cursors when done with them
db.close(); //<<<<<<<<<< not required but would result in an exception if returning a Cursor
return rv;
}
the underlying query being SELECT First_Name||" "||Middle_Name||" "||LastName AS fullname FROM student_table; so you concatenate the names as part of the query which returns just one dynamically created column named fullname.

How to store a row from a cursor

I want to pull a row from a data-filled cursor and store it in another object for other use.
my code:
SQLiteDatabase db = dbOpener.getReadableDatabase();
Cursor dataSet = db.query(WPTemplateDB.PRODUCT_TABLE,
null, //all columns
null, //where clause
null, //where clause args
null, null, null);//groupBy, having, orderBy
while (dataSet.moveToNext()){
Product product = new Product(dataSet);
pArray.add(product);
}
my storing object:
public Product(Cursor cursor){
productData = cursor;
}
public String getData(String column){
Log.d(column, productData.getColumnIndex(column)+"");
return productData.getString(productData.getColumnIndex(column));
}
Now, I am facing an error of "index 10 requested with a size of 10". What can I do to this?
Don't should using cursor is contructors for Product objects. It will leak memory because cursor must close when not use.
You should read data from cursor then send data to contructor Product like:
String productName = cursor.getString(0);// 0 is column name
......
cursor.close();
Product product = new Product(name);
Indexes are zero-based. It means that is size is 10, max index will be 9. From the code you've posted, everything is fine, so the error in some other place of your code.
Actually, this answer is inspired from #cuasodayleo, I just translate it to be another code.
SQLiteDatabase db = dbOpener.getReadableDatabase();
Cursor dataSet = db.query(WPTemplateDB.PRODUCT_TABLE,
new String[]{WPTemplateDB.PRODUCT_ID},
null, //where clause
null, //where clause args
null, null, null);//groupBy, having, orderBy
while (dataSet.moveToNext()){
Product product = new Product(dataSet.getInt(0), db);
pArray.add(product);
}
dataSet.close();
The Product object:
public Product(int pid, SQLiteDatabase db){
productData = db.query(WPTemplateDB.PRODUCT_TABLE,
null, //all columns
WPTemplateDB.PRODUCT_ID+"=?", //where clause
new String[]{pid+""}, //where clause args
null, null, null);//groupBy, having, orderBy
}
public String getData(String column){
Log.d("count", productData.getCount()+"");
if (productData.getCount()>0){
Log.d(column, productData.getColumnIndex(column)+"");
productData.moveToFirst();
return productData.getString(productData.getColumnIndex(column));
} else {
return null;
}
}

getting row id from sqlite using other fields as where condition

sir, how can i return the rowid of my database depending on the inputs name, number? this code just return the value 0 everytime. my primary key is KEY_ROWID. thanks for help in advance
//get rowid
public long getRowId(String name, String number)
{
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_NUMBER};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NUMBER+ "=" +number, null, null, null, null);
long rowid = c.getColumnIndex(KEY_ROWID);
return rowid;
}
here is how i access it
public void onClick(View arg0) {
nameChanged = sqlName.getText().toString();
numChanged = sqlNumber.getText().toString();
GroupDb info = new GroupDb(EditDetails.this);
info.open();
long rowid = info.getRowId(name, num);
info.updateNameNumber(rowid, nameChanged, numChanged);
Toast.makeText(getApplicationContext(), rowid+" "+nameChanged+" "+numChanged, Toast.LENGTH_LONG).show();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(EditDetails.this, searchResults);
mcba.updateResults(searchResults);
Toast.makeText(getApplicationContext(), "Update Successful!", Toast.LENGTH_LONG).show();
info.close();
}
});
From the fine manual:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
[...]
Returns
A Cursor object, which is positioned before the first entry.
So first you have step c into the result set and you can use moveToFirst for that:
c.moveToFirst();
Now you need to extract the rowid from the row that the cursor is pointing at. But getColumnIndex is for mapping a column name to a position in the row:
Returns the zero-based index for the given column name, or -1 if the column doesn't exist.
You're getting a zero from getColumnIndex because your KEY_ROWID is the first column in your SELECT query.
I think you're looking for getLong if you want to extract a long from the Cursor's result set:
long rowid = c.getLong(c.getColumnIndex(KEY_ROWID));
If you know the structure of your query (which you do), you could skip the getColumnIndex call and just use the known index:
long rowid = c.getLong(0);
And if all you're doing is looking up the rowid, you can SELECT just KEY_ROWID:
String[] columns = new String[]{KEY_ROWID};
There's no need to pull things out of the database that you're ignoring.

Android- Getting a single value from a database table using cursor

I'm using cursors to retrieve data from a database. I know how to retrieve entire columns to use on listviews and such, but I'm struggling to find a way to retrieve a single value.
Let's say I have a table with two columns ("_id" and "Name") and I have ten records (rows) in that table. How would I get, for example, the Name in the third row? Considering I defined a cursor that reads that table:
public Cursor getMyNameInfo() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String sqlTables = "MyNames";
qb.setTables(sqlTables);
Cursor c = qb.query(db, null, null, null,
null, null, null);
c.moveToFirst();
return c;
}
Instead of c.moveToFirst() use c.moveToPosition(2) (Cursor indexes are zero-based hence '2' is the third record).
Remember to check that the Cursor has valid data first though.
EDIT:
Once you've moved the cursor to the 3rd record as I explain above, use the following to just get the value of the "Name" column.
String theName = c.getString(getColumnIndex("Name"));
Cursor cursor = dbHelper.getdata();
System.out.println("colo" + cursor.getColumnCount() + ""
+ cursor.getCount());
cursor.moveToFirst();
if (cursor != null) {
while (cursor.isAfterLast() == false) {
String chktitle = title.trim().toString();
String str = cursor.getString(cursor.getColumnIndex("title"));
System.out.println("title :: "
+ cursor.getString(cursor.getColumnIndex("title")));
System.out.println("date :: "
+ cursor.getString(cursor.getColumnIndex("date")));
System.out.println("desc :: "
+ cursor.getString(cursor.getColumnIndex("desc")));
if (chktitle.equals(str) == true) {
tvAddfavorite.setText("Remove Favorite");
break;
}
cursor.moveToNext();
}
}
cursor.close();
Add a WHERE clause:
qb.appendWhere("_id = 2");
Thanks to the answers above I created the following method to give the value of an item from another column but in the same row.
public String getValueFromColumn(int position, String tableName, String columnToGetValueFrom) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(tableName);
Cursor c = qb.query(db, null, null, null,
null, null, null);
c.moveToPosition(position);
String neededValue = c.getString(c.getColumnIndex(columnToGetValueFrom));
return neededValue;
}
Hope it helps anyone.

android database adding more than needed

private static String[] FROM = { _ID, DESCRIPTION, DATE, TITLE };
//private static String ORDER_BY = _ID + " DESC" ;
private Cursor getEvents() {
// Perform a managed query. The Activity will handle closing
// and re-querying the cursor when needed.
SQLiteDatabase db = post.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null,
null, null);
startManagingCursor(cursor);
return cursor;
}
private void showEvents(Cursor cursor) {
TextView tv = new TextView(this);
// Stuff them all into a big string
StringBuilder builder = new StringBuilder(
"Saved events:\n" );
while (cursor.moveToNext()) {
// Could use getColumnIndexOrThrow() to get indexes
long id = cursor.getLong(0);
String description = cursor.getString(1);
String date = cursor.getString(2);
String title = cursor.getString(3);
builder.append(id).append(": " );
builder.append(description).append(": " );
builder.append(date).append(": " );
builder.append(title).append("\n" );
}
// Display on the screen
tv.setText(builder);
this.setContentView(tv);
}
So the showEvents function which is supposed to display the database is displaying a larger database than I created. It is showing 19 rows, yet I only called the insertorthrow function twice so it should have two rows, so I don't know how it can have more than 19 rows. I feel the problem may lie in my getEvents() function or showEvents() function which returns the cursor. Help would be appreciated.
Using db shell go to the location and delete the database .

Categories

Resources