I want to query the Contacts data and retrieve a contact name and a phone number with the following condition: if a contact has a mobile number then pick that number, else pick any number/first number the contact has. Is it possible to formulate this condition in a cursor query or would I have to do it within a custom cursor adapter?
This is the code I have at the moment. It works fine but it retrieves all numbers for all contacts, therefore I get duplicate names if a person has more than one contact.
private String WHERE_CONDITION = ContactsContract.Data.MIMETYPE + " = '" +
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'";
private String[] PROJECTION = {ContactsContract.Data.DISPLAY_NAME,
ContactsContract.Data.DATA1, ContactsContract.Data._ID };
private String SORT_ORDER = ContactsContract.Data.DISPLAY_NAME;
cursor = this.getContentResolver().query(
ContactsContract.Data.CONTENT_URI, PROJECTION, WHERE_CONDITION, null, SORT_ORDER);
Any help is much appreciated!
It would be much easier and simpler to put this logic in Java. Just retrieve all numbers and select the one you need. Typically you will have at most 3 numbers, may be 5. In any case overhead will be very low.
Related
i want to get sum of column price but it show -2 in total price
//Dbhandler
public Cursor gettotalp()
{
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor =database.rawQuery("select sum(totalprice) as total from " + TABLE_Users + ";", null);
Log.d(TAG, "gettotalp: "+cursor.getCount());
return cursor;
}
//showallsaleitemActivity
Cursor cursor = db.gettotalp();
int m=0;
/* while (cursor.moveToNext()) {
m += cursor.getInt(cursor.getColumnIndex("totalprice"));
}*/
for(int k = 0; k<=cursor.getCount();k++) {
m += (int) Integer.parseInt(String.valueOf(cursor.getColumnIndex("totalprice")));
}
int i=m;
tp.setText("" + m);
database table image
Your primary issue is that the column name in the cursor does not match the column name passed to the getColumnIndex method.
Secondly the value you want is stored in the column of the Cursor, it is not the value of the index of the column in the Cursor. As it is the first and only column the index will be 0 and not the sum of the totalprice column. Instead you need to get the value stored in the column based upon the index of the column using one of the Cursor get???? methods in this case you want to use either getInt or getString (if you want to use the value for calculations then getInt means that you don't have to do the parseInt from a String, if you only want to display the value then getString could be used).
I personally prefer to get the value using the get method more appropriate to the type of value being retrieved. Hence as it's an integer value then I have used getInt even though it's being used as a string.
I would suggest the following 2 snippets of code be used :-
// DBHanlder
public int gettotalp() {
int rv = 0;
String total_column = "total_price";
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor =database.rawQuery("select sum(totalprice) as " + total_column + " from " + TABLE_Users + ";", null);
Log.d(TAG, "gettotalp: "+cursor.getCount());
if (cursor.moveToFirst()) {
rv = cursor.getInt(cursor.getColumnIndex(total_column));
}
cursor.close();
return rv;
}
chances of mistakes reduced by using a variable for the column name alias.
The Cursor moveToFirst method will move to the first row in the Cursor.
When a Cursor is returned from the SQLiteDatabase methods that create a Cursor the Cursor is at a position that is BEFORE the first row, so a move is required.
All the Cursor move???? methods return false if the move cannot be made.
A Cursor should always be closed when it is done with. Not doing so can lead to errors who's underlying cause (such as file handles exhausted) is difficult to determine.
2nd Snippet :-
//showallsaleitemActivity
tp.setText(Integer.toString(gettotalp()));
Note
Instead of using
cursor.getInt(cursor.getColumnIndex(total_column))
As you are only returning a single value you could use
cursor.getInt(0)
then the column name is then irrelevant (if valid for the SQL). Personally I prefer to not use hard coded index unless necessary or overly complex to not use them.
The column that returns the sum in your query is not totalprice.
You aliased it as total.
To get it, use this:
Cursor cursor = db.gettotalp();
cursor.moveToFirst()
int m = cursor.getInt(cursor.getColumnIndex("total"));
or, since the query returns only 1 column:
int m = cursor.getInt(0);
You don't need the for loop, which in your code adds twice -1 and returns -2 because cursor.getColumnIndex("totalprice") returns -1 (since the column does not exist).
I am having issue querying my SQLITE database in Android. I have a table called "resets" with some values in them. Currently I only have one entry.
reset_timestamp | interval
1479442048 | 5
This is the query I was trying to execute. However, it returns zero results when I call cursor.getCount(). The query I want to execute is:
SELECT reset_timestamp FROM resets WHERE (reset_timestamp=1479442048);
I don't really want to use rawQuery(). I want to use query(). Here is my query statement.
SQLiteDatabase db = new PowerDbHelper(this).getWritableDatabase();
String[] resetsQueryColumns = {"reset_timestamp"};
String[] resetsQuerySelectArgs = {"1479442048"};
Cursor cursor = db.query("resets", resetsQueryColumns, "reset_timestamp=?",
resetsQuerySelectArgs, null, null, null);
However, getCount() returns 0 with this. On the other hand, this works fine and returns my result
cursor = db.rawQuery("select reset_timestamp from resets where (reset_timestamp=1479442048)", null);
and getCount() returns 1, what I want. Putting quotes around '?' gives me
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range
What am I doing wrong with query()?
"1479442048" is a string (you even wrote String in front of it). A string and a number are not equal.
The query function supports only string parameters, so you have to convert the string back into a number:
query(..., "reset_timestamp=CAST(? AS INT)", ...);
Alternatively, insert the number directly into the query:
query(..., "reset_timestamp=1479442048", null, ...);
From this question I can see how to get total unread: Get number of unread sms
I have searched for this on Google but unfortunately do not understand how I may go about this.
I am wondering if it is possible to get the number of texts (unread) for a specific number, or, to do more work on my end, get the number of unread texts for each phone number in the list, and then make my own comparisons. The end result would be that I am able to, for example, take the number 111 and see how many unread tests I have from them or to simply get an ArrayList or similar construct containing numbers and unread texts for each, through which to loop and compare against the number 111.
Use columns from android.provider.Telephony.TextBasedSmsColumns in your ContentResolver query to find SMS messages that are from a specific address and not read:
Use these column contants:
Telephony.TextBasedSmsColumns.ADDRESS
Telephony.TextBasedSmsColumns.READ
Something like this:
ContentResolver resolver = context.getContentResolver();
Cursor cursor = resolver.query(Telephony.Sms.CONTENT_URI,
null,
"WHERE " + Telephony.TextBasedSmsColumns.READ + " = ? and "
+ Telephony.TextBaseSmsColumns.ADDRESS + "= ?" ,
new String[]{"false", "+1 555 555 1212"},
Telephony.Sms.Conversations.DEFAULT_SORT_ORDER);
int unreadCount = cursor.getCount();
This is a strange problem, and I hope it has a simple solution. I have a database with encrypted values. I have created a cursor that will go through each of the entries in a table, decrypt the value from the column I need, and add the value to a variable, "total". I want the sum of all of the values in the column. Here is the code:
while (c.moveToNext())
{
strTotal = c.getString(c.getColumnIndexOrThrow(KEY_TOTAL));
strTotal = sc.decrypt(strTotal);
total = Float.valueOf(strTotal) + total;
}
Now, here's the strange part. Let's suppose I have two values in the database: 2 + 4. After each is decrypted, it will correctly add them: 6. Now, if the values are equal: 2 + 2, for instance, the method returns "2" instead of "4". This happens even if it is off by a decimal (2 + 2.01 = 4.01, but 2 + 2 still outputs 2 for example).
Is there something I am missing here? Thanks!
EDIT:
I've changed the code around just to see if the decryption was the problem and it is still giving me the same result:
float total = 0;
String strTotal = "10";
while (c.moveToNext())
{
try {
//strTotal = sc.decrypt(c.getString(c.getColumnIndex(KEY_TOTAL)));
total = Float.valueOf(strTotal) + total;
} catch (Exception e) {
Log.e(TAG, "exception", e);
}
}
This code is returning "10", even though there are 3 entries in the database! It looks like if two rows in the database have the same value in the KEY_TOTAL field, it is returning less results. Here is the query:
Cursor c = mDb.query(true, DATABASE_TABLE, new String[] {KEY_TOTAL}, KEY_TYPE + "=" + t, null, null, null, null, null);
If I pull the db and open it with a sqlite browser, and SELECT all of the rows, I am getting 3 still, however.
I just checked the SQLite documentation for Android (I'm not an Android developer) and I think I found your problem. The first argument to the query method is whether to select distinct rows. Since you're passing TRUE and you're only selecting one column, duplicates will be removed from the result, which is not what you want.
Changing your call to query to the following should fix your issue.
Cursor c = mDb.query(false, DATABASE_TABLE, new String[] {KEY_TOTAL},
KEY_TYPE + "=" + t, null, null, null, null, null);
Have you checked for thrown exceptions? Especially NumberFormatException? I'm guessing there is some other logic problem that is causing the loop to exit prematurely.
I'm new to SQLite and Java, and I'm trying to learn things on the fly. I have a column that has some numeric values in it, and I would like to get the sum of it and display it in a textview.
My current code is this:
public Cursor getTotal() {
return sqliteDatabase2.rawQuery(
"SELECT SUM(COL_VALUES) as sum FROM myTable", null);
}
I'm not sure if that code is correct, though.
I know that I'm supposed to fetch the results of that code, but I'm unsure how to do it. How can I get the results of this query into my Java code?
The sum will be returned as a result with one row and one column so you can use the cursor to fetch that value:
Cursor cursor = sqliteDatabase2.rawQuery(
"SELECT SUM(COL_VALUES) FROM myTable", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}