querying sqlite using string as where condition - android

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

Related

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

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.

How do i query SQLite table by string?

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.

Getting name and email from contact list is very slow

I'm implementing an AutoCompleteTextView and I need Name and E-Mail of all my contacts.
I found this snippet that I'm running asynchronously but it's very slow.
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);
while (emailCur.moveToNext()) {
String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
autoCompleteAdapter.add(name + " - " + email);
}
emailCur.close();
}
}
}
I'm performing a sort of inner query and I think that's the problem. Is there a way to tune it and make it faster?
private static final String[] PROJECTION = new String[] {
ContactsContract.CommonDataKinds.Email.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA
};
...
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION, null, null, null);
if (cursor != null) {
try {
final int contactIdIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID);
final int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int emailIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
long contactId;
String displayName, address;
while (cursor.moveToNext()) {
contactId = cursor.getLong(contactIdIndex);
displayName = cursor.getString(displayNameIndex);
address = cursor.getString(emailIndex);
...
}
} finally {
cursor.close();
}
}
few notes:
use just ContactsContract.CommonDataKinds.Email.CONTENT_URI to get information you need, see ContactsContract.CommonDataKinds.Email for information what columns you can query
use projection to get only those columns you really need, you save some memory and increase query performance
get column indexes only once, just before the while cycle
You should not query directly the ContactsContract.Contacts
Make just one query on the ContactsContract.CommonDataKinds with the email data kind.
The ContactsContract.CommonDataKinds.Email inherits a lot of other interfaces that you can use to build your projection. (see inherited constants from the documentation)
For example :
import android.provider.ContactsContract.CommonDataKinds.Email;
[...]
public static final String[] EMAILS_PROJECTION = new String[] {
Email._ID,
Email.DISPLAY_NAME_PRIMARY,
Email.ADDRESS
};
to be used with the
Email.CONTENT_URI
You can retrieve a lot of information (such as user id, user display name ...) directly from the email data kind.
EDIT:
I just realized you're trying to build an AutoCompleteTextView.
You should override the runQueryOnBackgroundThread method and the convertToString of your CursorAdapter and use the Email.CONTENT_FILTER_URI
I really strongly suggest you to take a look at the ApiDemo samples.
Especially the AutoComplete4.java sample that you can find HERE.
ContentResolver cr = mContext.getContentResolver();
Cursor cursor = mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, "HAS_PHONE_NUMBER <> 0", null, null);
if (cursor!= null)
{
final int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int numberIndex = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
final int idIndex= cursor.getColumnIndex(ContactsContract.Contacts._ID);
String displayName, number = null, idValue;
while (cursor.moveToNext())
{
displayName = cursor.getString(displayNameIndex);
idValue= cursor.getString(idIndex);
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, "contact_id = '" + idValue + "'", null, null);
phones.moveToFirst();
try
{
number = phones.getString(phones.getColumnIndex("data1"));
}
catch (CursorIndexOutOfBoundsException e)
{
}
phones.close();
userList.add(new ContactModel(displayName, number, null));
}
}

How can I put a string and an integer into the same array?

I have to following code. I want this to return an array e.g. arg[] that contains at arg[0] the number of the rows of my cursor and at arg[1] String(0) of my cursor. Since one is integer and the other is string I have a problem. Any ideas how to fix this?
public String[] getSubcategoriesRow(String id){
this.openDataBase();
String[] asColumnsToReturn = new String[] {SECOND_COLUMN_ID,SECOND_COLUMN_SUBCATEGORIES,};
Cursor cursor = this.dbSqlite.query(SECOND_TABLE_NAME, asColumnsToReturn, SECOND_COLUMN_SUBCATEGORIES + "= \"" + id + "\"", null, null, null, null);
String string = cursor.getString(0);
int count = cursor.getCount();
String arg[] = new String[]{count, string};
cursor.close();
return arg;
}
The cursor and the results and correct i just need to compine them to an array in order to return that.
Either:
Use an Object[] (an object array) instead of a String[] — not recommended, or
Create a new, meaningful class to hold the data.
public Subcategory getSubcategoriesRow(String id){
this.openDataBase();
String[] asColumnsToReturn = new String[] {SECOND_COLUMN_ID,SECOND_COLUMN_SUBCATEGORIES,};
Cursor cursor = this.dbSqlite.query(SECOND_TABLE_NAME, asColumnsToReturn, SECOND_COLUMN_SUBCATEGORIES + "= \"" + id + "\"", null, null, null, null);
String string = cursor.getString(0);
int count = cursor.getCount();
Subcategory toReturn = new Subcategory(count, string);
cursor.close();
return toReturn;
}

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