I just want to copy the incoming number and paste it to a text box. How can I do that?
Use a cursor to get any call log information you want.
String[] projection = {android.provider.CallLog.Calls._ID,
android.provider.CallLog.Calls.NUMBER,
CallLog.Calls.TYPE, CallLog.Calls.DATE};
final Cursor cursor = getActivity().getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, projection,
"type = " + CallLog.Calls.INCOMING_TYPE, null,
android.provider.CallLog.Calls.DATE + " DESC" + " LIMIT 200");
The cursor will result the number and time of call.
if (cursor.moveToFirst()) {
do {
try {
String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
String date = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE));
// Do anything with number and name
} catch (Exception e) {
}
} while (cursor.moveToNext());
}
cursor.close();
Related
I have a BIG transactions table. I want to to find a specific field(card number) in transactions inserted in last one minute, Therefore it is not reasonable to search the entire table. So i want to search just in top 20 rows.
Here is the my code:
public boolean isCardTapedInLastMinute(String date, String time,String UID) {
String oneMinuteBefore = getOneMinuteBefore(time);
String tables = TRX.TABLE_NAME;
String[] columns = {TRX._ID};
String selection = TRX.COLUMN_NAME_TRX_DATE + " = ? AND " +
TRX.COLUMN_NAME_TRX_TIME + " >= ? AND " +
TRX.COLUMN_NAME_CARD_ID + " = ?";
String[] selectionArgs = {date, oneMinuteBefore, UID};
String sortOrder = TRX.COLUMN_NAME_TRX_DATE
+ BusDBContract.SORT_ORDER_DESC
+ ", "
+ TRX.COLUMN_NAME_TRX_TIME
+ BusDBContract.SORT_ORDER_DESC;
String limit = "1";
Cursor cursor = query(selection, selectionArgs, columns, tables, sortOrder, limit);
if (null == cursor) {
return false;
}
if (!cursor.moveToFirst()) {
cursor.close();
return false;
}
return true;
}
and the query method:
private Cursor queryWith(String selection, String[] selectionArgs, String[] columns, String tables, String sortOrder, String limit) {
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(tables);
Cursor cursor;
try {
cursor = builder
.query(
mBusOH.getReadableDatabase(),
columns,
selection,
selectionArgs,
null,
null,
sortOrder,
limit);
} catch (SQLException e) {
Log.e(TAG, "[query]sql_exception: " + e.getMessage());
return null;
}
return cursor;
}
It is working correctly and it searches the entire table.
It takes about 50-100 ms to be performed for 15000 rows but it may be bigger and i want to optimize it by searching in top 20 rows.
What is the best way to do so?
EDIT: db scheme:
Hi I'm trying to update some rows incrementing a value in an int field but it doesn't work.
Here my snippet of code:
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables("TICKET");
String[] proj = new String[]{ "TICKET","NUMERO_ARTICOLO","QUANTITA","COMMESSA_IN","CODICE_SQUADRA"};
try{
Cursor cursor = queryBuilder.query(sqlDB, proj, selection, null, null, null, null);
sqlDB.beginTransaction();
cursor.moveToFirst();
while (cursor.moveToNext()){
String query = "UPDATE MATERIALE "
+ " SET RIMANENTE = RIMANENTE - " + cursor.getString(cursor.getColumnIndex("QUANTITA"))
+ " WHERE NUMERO_ARTICOLO = '"+cursor.getString(cursor.getColumnIndex("NUMERO_ARTICOLO"))+"'"
+" AND COMMESSA = '"+cursor.getString(cursor.getColumnIndex("COMMESSA_IN"))+"' "
+" AND CODICE_SQUADRA = '"+cursor.getString(cursor.getColumnIndex("CODICE_SQUADRA"))+"' ";
Log.d("update","Query: "+query);
sqlDB.rawQuery(query, null);
}
rowsUpdated = sqlDB.update("TICKET", values, selection, null);
sqlDB.setTransactionSuccessful();
Log.d("update","Aggiornate "+rowsUpdated+" righe");
sqlDB.endTransaction();
}catch (Exception e) {
e.printStackTrace();
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(CONTENT_URI, null);
return rowsUpdated;
Last query is working
rowsUpdated = sqlDB.update("TICKET", values, selection, null);
but the while cycle is not working.
What I do wrong? Maybe the UPDATE SET RIMANENTE = RIMANENTE - " + cursor.getString(cursor.getColumnIndex("QUANTITA"))
I want the cycle (while) and the last update in the same transaction.
Sqlite uses file-based locking while you are inserting-updating or selecting the rows from database. This means when you are fetching the records from database using Select query and until the cursor with that select statement is not closed you can not insert update or delete in mean time.
So you should close the cursor and then use execSQL in place of rawQuery to fire update
try
{
Cursor cursor = queryBuilder.query(sqlDB, proj, selection, null, null, null, null);
//sqlDB.beginTransaction();
List<String> updateSql = new ArrayList<String>();
try
{
cursor.moveToFirst();
while (cursor.moveToNext())
{
updateSql.add( "UPDATE MATERIALE "
+ " SET RIMANENTE = RIMANENTE - " + cursor.getString(cursor.getColumnIndex("QUANTITA"))
+ " WHERE NUMERO_ARTICOLO = '"+cursor.getString(cursor.getColumnIndex("NUMERO_ARTICOLO"))+"'"
+" AND COMMESSA = '"+cursor.getString(cursor.getColumnIndex("COMMESSA_IN"))+"' "
+" AND CODICE_SQUADRA = '"+cursor.getString(cursor.getColumnIndex("CODICE_SQUADRA"))+"' ");
Log.d("update","Query: "+query);
}
}
finally
{
cursor.close();
}
try
{
sqlDB.beginTransaction();
for (String query : updateSql)
{
sqlDB.execSQL(query, null); //Here it should be execSQL instead of rawQuery
}
rowsUpdated = sqlDB.update("TICKET", values, selection, null);
sqlDB.setTransactionSuccessful();
Log.d("update","Aggiornate "+rowsUpdated+" righe");
}
finally
{
sqlDB.endTransaction();
}
}
catch (Exception e)
{
e.printStackTrace();
}
EDIT If I read documentation it is clearly mentioned that
For UPDATE statements, use any of the following instead.
update(String, ContentValues, String, String[])
updateWithOnConflict(String, ContentValues, String, String[], int)
You'd better use SQL facilities to accomplish this task:
try {
sqlDB.execSQL("UPDATE TICKET SET RIMANENTE = RIMANENTE - QUANTITA");
} catch (Exception e) {
e.printStackTrace();
}
This will, in a single statement - so, in a single transaction also - subtract QUANTITA to RIMANENTE in all rows from table TICKET.
EDIT:
UPDATE TICKET SET RIMANENTE = RIMANENTE - QUANTITA WHERE QUANTITA IS NOT NULL
is preferable, because if QUANITTA is not defined, i.e. NULL, RIMANENTE will be nulled. WHERE clause prevents such from happen.
I would like to query on phonenumber to obtain the rawcontactID.
The only thing I know of the contact is the given phonenumber, but for my function I need to have the rawcontactID. I got a working code but now I did use 2 seperate queries. What I would like to have is 1 query that can do both just to save some query time.
my code:
Uri uri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String[] columns = new String[]{Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER, Phone._ID };
Cursor cursor = contentResolver.query(uri, columns, null, null, null);
if(cursor!=null) {
int clenght = cursor.getCount();
while(cursor.moveToNext()){
//contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
id = cursor.getString(cursor.getColumnIndex(Phone.CONTACT_ID));
}
cursor.close();
}
Cursor pCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data.RAW_CONTACT_ID}, ContactsContract.Data.CONTACT_ID+" = "+ id, null, null);
if(pCur!=null) {
int clenght = pCur.getCount();
while(pCur.moveToNext()){
//contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
id = pCur.getString(pCur.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
}
pCur.close();
}
thanks in advance
Edit:
My code above works fine, but I am still looking for increasing speed for large number of contacts. Therefore I will give a bounty if someone comes with a solution to combine my queries.
private String[] getRawContactIdFromNumber(String givenNumber){
List<String> rawIds = new ArrayList<String>();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID},ContactsContract.CommonDataKinds.Phone.NUMBER + "='"+ givenNumber +"'",null, ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phones.moveToNext())
{
rawIds.add( phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID)));
Log.v("contacts","Given Number: " + givenNumber + "Raw ID: " +rawIds.get(rawIds.size() - 1));
}
phones.close();
String[] ret = new String[0];
return rawIds.toArray(ret);
}
Edited to only include the raw id in the cursor for efficiency. Also changed return type to array in case multiple contacts have the same number.
Please try
String phonenumber = "input your phone number";
Cursor pCur = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[] { ContactsContract.Data.RAW_CONTACT_ID,
Phone.CONTACT_ID }, Phone.NUMBER + " = " + phonenumber,
null, null);
if (pCur != null) {
while (pCur.moveToNext()) {
String contactID = pCur.getString(pCur
.getColumnIndex(Phone.CONTACT_ID));
String Rowid = pCur.getString(pCur
.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
Log.e("RAW_CONTACT_ID", Rowid);
Log.e("CONTACT_ID", contactID);
}
pCur.close();
}
Now you can get Both CONTACT_ID & RAW_CONTACT_ID in single query.
I am developing an application, where I need to fetch the phone number from the contacts corresponding to the name provided. I have tried many codes but none of them seem to work.
Here is the code I'm currently using now
public static String getContactPhoneNumber(Context context, String contactName, int type) {
String phoneNumber = null;
String[] whereArgs = new String[] { contactName, String.valueOf(type) };
Log.d(TAG, String.valueOf(contactName));
Cursor cursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.Contacts.DISPLAY_NAME + " = ? and "
+ ContactsContract.CommonDataKinds.Phone.TYPE + " = ?", whereArgs, null);
int phoneNumberIndex = cursor
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
Log.d(TAG, String.valueOf(cursor.getCount()));
if (cursor != null) {
Log.v(TAG, "Cursor Not null");
try {
if (cursor.moveToNext()) {
Log.v(TAG, "Moved to first");
Log.v(TAG, "Cursor Moved to first and checking");
phoneNumber = cursor.getString(phoneNumberIndex);
}
} finally {
Log.v(TAG, "In finally");
cursor.close();
}
}
Log.v(TAG, "Returning phone number");
return phoneNumber;
}
On passing Contact Name (say: John Doe) and type (2 which is int value for Mobile Type), the phone number returned is null even though the contact "John Doe" exists in my contact list.
Please help!!!
Try this
instead of ContactsContract.CommonDataKinds.Phone.CONTENT_URI Pass
ContactsContract.Contacts.CONTENT_URI parameter to query method.
I am trying to birthday information to a contact. I use lookupkey to identify my contacts (as it is safer than just relying on contactId). In order to be able to insert the Event into the database i need a raw_contact_id ... so i'm trying to get this id:
String where = ContactsContract.Data.LOOKUP_KEY + " = ? AND "
+ ContactsContract.Data.MIMETYPE + " = ?";
String[] params = new String[] { lookupKey,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
Cursor cursor = contentResolver.query(
ContactsContract.Data.CONTENT_URI, null, where, params, null);
if (cursor.moveToFirst()) {
birthdayRow = cursor.getInt(idIdx);
long rawContactId = cursor.getLong(cursor
.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
}
The problem is that if there is not birthday event set for a contact then this cursor i receive is empty ... and i don't know how to insert this event without a raw_contact_id. In order to insert the event i do the folowing:
values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
values.put(ContactsContract.Data.MIMETYPE, Event.CONTENT_ITEM_TYPE);
values.put(ContactsContract.CommonDataKinds.Event.START_DATE,
birthdayStartDate);
values.put(ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY);
values.put(ContactsContract.CommonDataKinds.Event.START_DATE,
context.getString(R.string.birthday_label));
if (birthdayRow >= 0) {
int result = contentResolver.update(
ContactsContract.Data.CONTENT_URI, values,
ContactsContract.Data._ID + " = " + birthdayRow, null);
Log.i("ContactList", "update result: " + result);
} else {
Uri result = contentResolver.insert(
ContactsContract.Data.CONTENT_URI, values);
Log.i("ContactList", "update result: " + result);
}
So please advice what shall i do, is there any way to add this event to the ContactData whitout a raw_contact id? Also i find strange the fact that for other ContactData like nickname i am doing the same thing and i dont get an empty cursor for the params
String[] params = new String[] { String.valueOf(lookupKey),
ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE };
even if the contact has no nickname.
Use this to get the raw contact id before performing the insert.
long rawContactId = -1;
String[] projection = new String[]{ContactsContract.CommonDataKinds.Event.RAW_CONTACT_ID};
String selection = ContactsContract.CommonDataKinds.Event.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{
String.valueOf(bdayContact.getId()) };
Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, selection, selectionArgs, null);
try {
if (c.moveToFirst()) {
rawContactId = c.getLong(0);
}
} finally {
c.close();
}