I have written method which should return string with data from select query, but it doesn't work perfectly as I would like, here is method:
public String selectorDanych(String kolumna, String log){
String test = "Select "+ kolumna + " from "+ Usr_TABLE+ " where "+colLogin + " ='" +log+"';";
Cursor cursor2 = sqLiteDatabase.rawQuery(test, null);
return cursor2.toString();
}
it returns some kind of string but, it is not the thing I want [ the string it returns is something like "SQLite.database.#" etc
You're returning the internal name of the Cursor you got from the query, not any data from the query results.
You should use something like:
cursor2.moveToFirst(); // position the cursor at the first returned row
String col = cursor2.getString(the_index_of_the_column_you_want);
cursor2.close();
return col;
Make sure you test for errors though (there might be no rows returned at all), and read the Cursor API docs.
Rewrite your code as
public String selectorDanych(String kolumna, String log){
String test = "Select "+ kolumna + " from "+ Usr_TABLE+ " where "+colLogin + " ='" +log+"';";
Cursor cursor2 = sqLiteDatabase.rawQuery(test, null);
//Write these codes
if(cursor2.moveToFirst()) {
cursor2.close(); //You should close your cursor
return cursor2.getString(0); //index of your kolumna field
} else {
cursor2.close(); //You should close your cursor
return null; //Return some error msg, to notify that data not found
}
}
You can use the code below. You may catch exception after the try block. Even if you don't, you're guaranteed that the close() on the cursor will be called! I also suggest to always use English names for your vars.
public String selectorDanych(String kolumna, String log){
String test = "Select "+ kolumna + " from "+ Usr_TABLE+ " where "+colLogin + " ='" +log+"';";
Cursor cursor2 = sqLiteDatabase.rawQuery(test, null);
if (cursor2 != null && cursor2.moveToFirst()) {
try { //use try - finally to close the cursor in the finally block
int index_kolumna = cursor2.getColumnIndexOrThrow(kolumna);
String kolumna_val = cursor2.getString(index_kolumna);
} finally {
if (cursor2 != null && !cursor2.isClosed()) {
cursor2.close();
}
}
}
Related
I am using following to delete a number from call log. The method works fine, but for those number which contains () and - does not work fine.
public void deleteNumber(Context context, String mobile_number) {
String Calls = "content://call_log/calls";
Uri UriCalls = Uri.parse(Calls);
Cursor cur = context.getContentResolver().query(UriCalls, null, null, null, null);
Toast.makeText(context, "The number to be deleted is: " + mobile_number, Toast.LENGTH_LONG).show();
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String query = "NUMBER='" + mobile_number + "'";
int i = context.getContentResolver().delete(UriCalls, query, null);
if (i > 0) {
Toast.makeText(context, "The number " + mobile_number + " is deleted.", Toast.LENGTH_LONG).show();
break;
}
}
}
cur.close();
}
Number which are saved in this format are not deleted. Please help me to solve this.
Edit :
The following did the trick:
mobile_number = mobile_number.replaceAll("[^0-9]","");
I am using a method, which returns a mobile number. This number contains all characters including (), spaces etc. It need to be filtered.
Replace:
String query = "NUMBER='" + mobile_number + "'";
int i = context.getContentResolver().delete(UriCalls, query, null);
with:
String query = "NUMBER=?";
String[] args={ mobile_number };
int i = context.getContentResolver().delete(UriCalls, query, args);
and see if you have better luck. ( and ) are probably reserved characters and would need to be escaped. Using query parameters would solve that for you.
I'm running the following query,
Cursor c = db.rawQuery("SELECT SUM(surveycount) FROM surveyDB WHERE species = " + "'" + szSpecies + "' AND location = " + "'" + szLocation + "'", null);
With the database column "surveycount" declared as an INT when the table is created. The below code works fine except when no records are returned that have the target string values for szSpecies and szLocation at which point szSum is shown as null.
if (c.moveToFirst()) {
szSum = c.getString(0);
c.close();}
else{
//do nothing
Toast.makeText(getActivity().getApplicationContext(),"It was NULL",Toast.LENGTH_LONG).show();
}
Toast.makeText(getActivity().getApplicationContext(),"Surveycount SUM = "+szSum+" .",Toast.LENGTH_LONG).show();
How can I catch this errant cursor output?
First check if the cursor is not null and then see if the cursor.getcount() is greater than 0, only then try to retrieve values from cursor.
Updated code as below:
Cursor c = db.rawQuery("SELECT SUM(surveycount) FROM surveyDB WHERE species = " + "'" + szSpecies + "' AND location = " + "'" + szLocation + "'", null);
szSum="";
if(c!=null && c.getCount()>0)
{
c.moveToFirst()
szSum = c.getString(0);
c.close();
} else{
//do nothing
Toast.makeText(getActivity().getApplicationContext(),"It was NULL",Toast.LENGTH_LONG).show();
}
if(!szSum.equals(""))
Toast.makeText(getActivity().getApplicationContext(),"Surveycount SUM = "+szSum+" .",Toast.LENGTH_LONG).show();
getCount (): Returns the numbers of rows in the cursor
Okay, changing out this,
szSum = c.getString(0);
for this
iSum=c.getInt(0);
appears to have solved the problem with zero being returned when querying location or species qualifier combinations that lack common counts.
Thanks for the help...
public boolean findContact(String phoneNumber) {
boolean exists = false;
Cursor mCursor = mDb.rawQuery("SELECT * FROM " + SQLITE_TABLE + " WHERE " + KEY_PHONENUMBER + " = " + phoneNumber, null);
if (mCursor.moveToFirst()) {
exists = true;
} else exists = false;
return exists;
}
It is supose to return true when a row with telephone number exists (format is +441212312312 - String ). The problem is that it always return false, even if such a row exists. I think that a problem is with WHERE clause, but LIKE don't work either. How can I do this ?
thanks for your response
i suggest you that use query, insert, update or delete clauses directly from SQLiteDatabase object instance ;)
And see link below to know which values you will have returned
SQLiteDatabase Object
And i suggest too that if you just want if it exists don't ask about * ... ask about _id because it's primary key it has a index ;)) <-- it means faster
Here i seek a specific row:
public Cursor getEnvio(final String empresa_p, final String albaran_p) {
return db.query(Envio.KEY_ENVIO, new String[] { Envio.KEY_ID,
Envio.KEY_ALBARAN, Envio.KEY_LINEA, Envio.KEY_TIPO,
Envio.KEY_DESTINATARIO, Envio.KEY_DIR, Envio.KEY_POBLACION,
Envio.KEY_POBLACION, Envio.KEY_PRIORIDAD, Envio.KEY_INCIDENCIA,
Envio.KEY_EMP, Envio.KEY_CPOSTAL }, Envio.KEY_EMP + " = ? AND "
+ Envio.KEY_ALBARAN + " = ? ", new String[] { empresa_p,
albaran_p }, null, null, Envio.KEY_LINEA);
}
I have the following function for SQLite select statement
public Boolean itemFound(String cartId,Long ItemId){
SQLiteDatabase db = this.getReadableDatabase();
Log.d("search",cartId+"--"+ItemId);
try {
String where = COL_ITEM_CART_ID+"='"+cartId+"' and "+COL_ITEM_ID+" ="+ ItemId+"";
Log.d("where===============", where);
String columns[] = new String[] { COL_ITEM_ID,COL_ITEM_NAME, COL_ITEM_PRICE, COL_ITEM_ADDDATE,COL_ITEM_QUANTITY,COL_ITEM_CART_ID }; // > null means * (all)
Cursor c = db.query(TABLE_NAME,
columns ,
COL_ITEM_CART_ID+"='?' and "+ COL_ITEM_ID + "=?" ,
new String[]{cartId,String.valueOf(ItemId)},
null,
null,
COL_ITEM_ADDDATE+" desc");
int numRows = c.getCount();
c.close();
db.close();
if(numRows>0)
return true;
else
return false;
} catch (SQLException e) {
db.close();
return false;
}
}
where the parameters are :
Long type itemId= 9882889921
String type cartId = ca1745ef-24eb-4da8-a1ea-9650d78ba5c0
Despite there is recode with these data. the returned rows is 0 , why ?
You have wrapped a ? in single quotes, change this:
COL_ITEM_CART_ID+"='?' and "+ COL_ITEM_ID + "=?"
The line above is trying to literally match COL_ITEM_CART_ID to a question mark, change it like this:
COL_ITEM_CART_ID + "=? and "+ COL_ITEM_ID + "=?"
The query method will sanitize your data input for you, so when you wrap the ?s with apostrophes, the apostrophes become part of the input string itself. This is causing your query to return 0 rows.
To fix the problem, remove change all instances of '?' to ?.
I wonder if there is an easy way to see the SQL generated by the SQLiteQueryBuilder class in Android? I want to use this for debugging purposes.
I looked around and searched but couldn't find anything. Either it's not easy or it's super obvious.
What it basically does is calling the SQLiteQueryBuilder#buildQueryString static method, so you can try to call that method passing the correct parameters. This is how the method looks like:
public static String buildQueryString(
boolean distinct, String tables, String[] columns, String where,
String groupBy, String having, String orderBy, String limit) {
if (TextUtils.isEmpty(groupBy) && !TextUtils.isEmpty(having)) {
throw new IllegalArgumentException(
"HAVING clauses are only permitted when using a groupBy clause");
}
if (!TextUtils.isEmpty(limit) && !sLimitPattern.matcher(limit).matches()) {
throw new IllegalArgumentException("invalid LIMIT clauses:" + limit);
}
StringBuilder query = new StringBuilder(120);
query.append("SELECT ");
if (distinct) {
query.append("DISTINCT ");
}
if (columns != null && columns.length != 0) {
appendColumns(query, columns);
} else {
query.append("* ");
}
query.append("FROM ");
query.append(tables);
appendClause(query, " WHERE ", where);
appendClause(query, " GROUP BY ", groupBy);
appendClause(query, " HAVING ", having);
appendClause(query, " ORDER BY ", orderBy);
appendClause(query, " LIMIT ", limit);
return query.toString();
}