Get a single row from a SQLite DB without using an ID - android

The below code gives me single row using id:
public DataObject getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_PHN, KEY_PTYPE, KEY_PDATE ,KEY_PNAME, KEY_PNOTE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null) cursor.moveToFirst();
DataObject contact = new DataObject(Integer.parseInt(cursor.getString(0)),cursor.getString(1),
cursor.getString(2), cursor.getString(3),cursor.getString(4),cursor.getString(5));
cursor.close();
return contact;
}
but I want is using a string,for eg: if my database is as below, then I want get the whole row, when I say name2 (that means it should return address2 and phno2)
name1 address1 phnno1
name2 address2 phnno2
name3 address3 phnno3
name4 address4 phnno4

I use your example to build my answer.
You can do :
Cursor cursorTable = db.query(CONTACTS,
new String[]{NAME, ADDRESS, PHNNO},
NAME + "= ?",
new String[]{"name2"},
null,
null,
null);
But if you want this to return only information for name2 you have to be sure there is only one row with "name2" as NAME

Related

how to use where clause in cursor query in sqlite

I want only particular rows that has "E" inside the column "TX_IDT". I used the following code but apps stops. In logcat the error says it is at db.query line.
public Cursor getAllRows( ) {
String where = null;
SQLiteDatabase db = helper.getReadableDatabase();
String[] columns = { VivzHelper.UID, helper.UID,helper.NAME,helper.TX_IDT};
String whereClause = "TX_IDT = ? ";
String[] whereArgs = new String[] { "E" };
Cursor c = db.query( VivzHelper.TABLE_NAME, columns,whereClause,whereArgs, null, null, NAME + " ASC"); // for out btn
if (c != null) {
c.moveToFirst();
}
return c;
}
`
Seems like you want record's containing "E" ,
Try this
Cursor c = db.query(VivzHelper.TABLE_NAME, columns, helper.TX_IDT +" LIKE '%E%' ", null, null, null, null);

Android SQLite selection argument

I've got an SQLite database in my Android app. I want to be able to select a random row based on the YEAR column in the database. I'm already able to select a random row from the entire table like so:
public String[] getTEST3RandChVerScrip() {
Cursor cursor = this.db.query("provtable Order BY RANDOM() LIMIT 1",
new String[] { KEY_MAKE, KEY_MODEL, KEY_NOTE }, null,
null, null, null, null);
if (cursor != null) {
for (cursor.moveToFirst(); !cursor.isAfterLast();) {
String colStrings[] = new String[3];
colStrings[0] = cursor.getString(0);
colStrings[1] = cursor.getString(1);
colStrings[2] = cursor.getString(2);
return colStrings;
}
}
return null;
}
But when I try and add a selection argument, the app errors out. Here's where I've added the selection argument:
public String[] getTEST3RandChVerScrip() {
Cursor cursor = this.db.query("provtable Order BY RANDOM() LIMIT 1",
new String[] { KEY_MAKE, KEY_MODEL, KEY_NOTE }, KEY_YEAR = "1964",
null, null, null, null);
if (cursor != null) {
for (cursor.moveToFirst(); !cursor.isAfterLast();) {
String colStrings[] = new String[3];
colStrings[0] = cursor.getString(0);
colStrings[1] = cursor.getString(1);
colStrings[2] = cursor.getString(2);
return colStrings;
}
}
return null;
}
Is the syntax incorrect in KEY_YEAR = "1964"? If so any idea what it should be?
As per tyczj's answer I've modified the query to:
Cursor cursor = this.db.query("provtable Order BY RANDOM() LIMIT 1",
new String[] { KEY_MAKE, KEY_MODEL, KEY_NOTE }, KEY_YEAR + "=?",
new String[] {"1964"}, null, null, null);
... and I'm still getting an error that says: 06-20 15:18:33.644: E/AndroidRuntime(4758): android.database.sqlite.SQLiteException: near "WHERE": syntax error: , while compiling: SELECT make, model, note FROM provtable Order BY RANDOM() LIMIT 1 WHERE year=?
You shouldn't put order by in the table name area
this.db.query("provtable",
new String[] { KEY_MAKE, KEY_MODEL, KEY_NOTE }, KEY_YEAR + "=?",
new String[] {"1964"}, null, null, "RANDOM() LIMIT 1");
it should be
KEY_YEAR+"=1964"
however better syntax wound be to put your selection as KEY_YEAR+"=?" and then you selectionArgs should be new String[] {"1964"}
also post the error

SQLite, getting last item in table

I need some help with using the database that I created. I need to access the last item in the database. This is my code that gets a single item. How can I change it to only get the last?
// Getting single user
User getuser(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT,
KEY_GOAL, KEY_BMI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if(cursor!=null && cursor.getCount()!=0){
cursor.moveToFirst();
}
User user = new User(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getInt(2),cursor.getInt(3), cursor.getInt(4),
cursor.getString(5), cursor.getFloat(6));
return user;
}
Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT,
KEY_GOAL, KEY_BMI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, KEY_ID + " DESC", "LIMIT 1");
if the id uniquely identifies the user then you will be getting only one row as the result for the id you are passing so you dont have to worry about it is the last or first in the database. if it is just that you want the last row in your database then you dont have to pass an id you can do a select * and after retrieving move the cursor to last ie cursor.moveToLast().
Do this if you just want the last row
User getuser() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT,
KEY_GOAL, KEY_BMI }, null,
null, null, null, null, null);
if(cursor!=null && cursor.getCount()!=0){
cursor.moveToLast();
}
User user = new User(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getInt(2),cursor.getInt(3), cursor.getInt(4),
cursor.getString(5), cursor.getFloat(6));
return user;
}
and your call can be like this
User currentUser = db.getUser();
If you are passing an id to get a user details an the id uniquely identifies the user then what you have done will work
Are you perhaps looking for cursor.moveToLast()? This will move the cursor to the last record selected from your query. You can then get the fields values as usual using cursor.getString(n) etc.
You simply need to change a little in your code,
// Getting single user
User getuser(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT,
KEY_GOAL, KEY_BMI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if(cursor!=null && cursor.getCount()!=0){
cursor.moveToLast(); // Change here
}
User user = new User(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getInt(2),cursor.getInt(3), cursor.getInt(4),
cursor.getString(5), cursor.getFloat(6));
return user;
}
Try this one:
Cursor c = db.rawquery("Select *from tablename");
c.movetoLast();
and if you want to get the data from last to first use this codes:
Cursor c = db.rawquery("Select *from tablename");
c.movetoLast();
int count = c.getCount();
for(int i = 0; i < count; i++){
c.movetoPrevious();
}

My android sqlite database app gets close when I search the name which does not exist in the table

Here is a code/method to find if some name exists in the table or not..
Contact getContact(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
db.close();
cursor.close();
// return contact
return contact;
}
I already have a function to get all names in an arrayList. I can call it before calling the above function to solve my problem. But I want to ask about is there any other (straight) way to do it
When you call cursor.moveToFirst() it will return true if there is a valid result there, or false in the case no results are found. If cursor.moveToFirst() returns false, then calling any of the getXXX() methods will fail.
Try something like this:
if( cursor.moveToFirst() )
{
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
}
cursor.close();
Note that the Cursor returned from SQLiteDatabase.query is guaranteed to be non-null.
if (cursor == null)
Toast.makeText(getApplicationContext(), "No Records Exist", Toast.LENGTH_SHORT).show();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if(cursor.moveToFirst()){
do {
Double lat = cursor.getDouble(2);
Double lon = cursor.getDouble(1);
} while (trackCursor.moveToNext());
}
Here is a code for getting all the contacts in a list from the table...
/**
* Getting all the contacts in the database
*/
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return contact list
return contactList;
}
Then it is invoked in another function that returns "true" if name is present in the table "false" otherwise...
/**
* checks if name already present in the database
* #param name
* #return
*/
public boolean checkDbData(String name){
List<Contact> contactList =getAllContacts();
boolean checkName = false ;
for(Contact cn: contactList){
String dbName = cn.getName();
if(name.equals(dbName)){
checkName = true ;
}
}
return checkName;
}
And if this function returns "true", then the above given function is invoked to get the contacti.e.
Contact getContact(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
db.close();
cursor.close();
// return contact
return contact;
}
Note: we can also get this contact from the contactList, both can be used to get the required contact (i.e. "name" in this case)

How do I order my SQLITE database in descending order, for an android app?

What is the most efficient method of showing my data in descending order?
public String getRank() {
String[] rank = new String[]{ KEY_ROWID };
Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, null); //reading information from db.
String rankResult = "";
int iRow = c.getColumnIndex(KEY_ROWID); //Cursor looking for column setting equal to these ints.
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
//Move to first row - where cursor starts and moves to next row as long it is not after last row.
rankResult = rankResult + c.getString(iRow) + "\n";
//Returning value of row that it is currently on.
}
return rankResult; //returning result
}
public String getName() {
String[] name = new String[]{ KEY_NAME };
Cursor c = scoreDb.query(DATABASE_TABLE, name, null, null, null, null, null); //reading information from db.
String nameResult = "";
int iRow1 = c.getColumnIndex(KEY_NAME); //Cursor looking for column setting equal to these ints.
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
//Move to first row - where cursor starts and moves to next row as long it is not after last row.
nameResult = nameResult + c.getString(iRow1) + "\n";
//Returning value of row that it is currently on.
}
return nameResult; //returning result
}
public String getScore() {
String[] score = new String[]{ KEY_SCORE };
Cursor c = scoreDb.query(DATABASE_TABLE, score, null, null, null,null, null); //reading information from db.
String scoreResult = "";
int iRow2 = c.getColumnIndex(KEY_SCORE); //Cursor looking for column setting equal to these ints.
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
//Move to first row - where cursor starts and moves to next row as long it is not after last row.
scoreResult = scoreResult + c.getString(iRow2) + "\n";
//Returning value of row that it is currently on.
}
return scoreResult; //returning result
}
Query has two syntax, the syntax you are using, last column represents orderBy, you just need to specify on what column you want to do orderBy +"ASC" (or) orderBy +"DESC"
Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
Refer this documentation to understand more about query() method.
return database.rawQuery("SELECT * FROM " + DbHandler.TABLE_ORDER_DETAIL +
" ORDER BY "+DbHandler.KEY_ORDER_CREATED_AT + " DESC"
, new String[] {});
Cursor c = scoreDb.query(Table_Name, score, null, null, null, null, Column+" DESC");
Try this
According to docs:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
and your ORDER BY param means:
How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the default
sort order, which may be unordered.
So, your query will be:
Cursor cursor = db.query(TABLE_NAME, null, null,
null, null, null, KEY_ITEM + " DESC", null);
public List getExpensesList(){
SQLiteDatabase db = this.getWritableDatabase();
List<String> expenses_list = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME ;
Cursor cursor = db.rawQuery(selectQuery, null);
try{
if (cursor.moveToLast()) {
do{
String info = cursor.getString(cursor.getColumnIndex(KEY_DESCRIPTION));
expenses_list.add(info);
}while (cursor.moveToPrevious());
}
}finally{
cursor.close();
}
return expenses_list;
}
This is my way of reading the record from database for list view in descending order. Move the cursor to last and move to previous record after each record is fetched. Hope this helps~
Cursor c = myDB.rawQuery("SELECT distinct p_name,p_price FROM products order by Id desc",new String[]{});
this works for me!!!
you can do it with this
Cursor cursor = database.query(
TABLE_NAME,
YOUR_COLUMNS, null, null, null, null, COLUMN_INTEREST+" DESC");
SQLite ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns.
Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
TABLE_NAME,
rank,
null,
null,
null,
null,
COLUMN + " DESC",
null);
We have one more option to do order by
public Cursor getlistbyrank(String rank) {
try {
//This can be used
return db.`query("tablename", null, null, null, null, null, rank +"DESC",null );
OR
return db.rawQuery("SELECT * FROM table order by rank", null);
} catch (SQLException sqle) {
Log.e("Exception on query:-", "" + sqle.getMessage());
return null;
}
}
You can use this two method for order
This a terrible thing! It costs my a few hours!
this is my table rows :
private String USER_ID = "user_id";
private String REMEMBER_UN = "remember_un";
private String REMEMBER_PWD = "remember_pwd";
private String HEAD_URL = "head_url";
private String USER_NAME = "user_name";
private String USER_PPU = "user_ppu";
private String CURRENT_TIME = "current_time";
Cursor c = db.rawQuery("SELECT * FROM " + TABLE +" ORDER BY " + CURRENT_TIME + " DESC",null);
Every time when I update the table , I will update the CURRENT_TIME for sort.
But I found that it is not work.The result is not sorted what I want.
Finally, I found that, the column "current_time" is the default row of sqlite.
The solution is, rename the column "cur_time" instead of "current_time".
About efficient method. You can use CursorLoader. For example I included my action. And you must implement ContentProvider for your data base. https://developer.android.com/reference/android/content/ContentProvider.html
If you implement this, you will call you data base very efficient.
public class LoadEntitiesActionImp implements LoaderManager.LoaderCallbacks<Cursor> {
public interface OnLoadEntities {
void onSuccessLoadEntities(List<Entities> entitiesList);
}
private OnLoadEntities onLoadEntities;
private final Context context;
private final LoaderManager loaderManager;
public LoadEntitiesActionImp(Context context, LoaderManager loaderManager) {
this.context = context;
this.loaderManager = loaderManager;
}
public void setCallback(OnLoadEntities onLoadEntities) {
this.onLoadEntities = onLoadEntities;
}
public void loadEntities() {
loaderManager.initLoader(LOADER_ID, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(context, YOUR_URI, null, YOUR_SELECTION, YOUR_ARGUMENTS_FOR_SELECTION, YOUR_SORT_ORDER);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}

Categories

Resources