I try to check if contact is favorite(starred) in Android. Here what I do:
String starred = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.STARRED));
Boolean isFavorite;
if(starred=="1"){
isFavorite = true;
}else{
isFavorite = false;
}
My isFavorite always returns false, even if starred returns 1.
What is wrong with my code?
public void checkFavorite(){
Cursor getContactNumber = getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.NUMBER+" LIKE ?",
new String[] { "%"+number }, //number is your number to check
null);
if(getContactNumber != null) {
while (getContactNumber.moveToNext()) {
String favcheck = getContactNumber.getString(getContactNumber.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
}
if(favcheck.equals("1")){
// contact is fav
}else{
// contact is not fav
}
}
}
You need to check your result with equals method. If you do it with ==, you try to check if two variables assignment to the same object. And obviously "1" and starred are different objects.
Try this:
if ("1".equals(starred) {
Related
i have a huge problem with duplicated contacts.
After sorting array with:
Collections.sort(mAllContacts);
I'm reading contacts with :
ContentResolver cr = mContext.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts = new AllContacts(name, phoneNo);
mAllContacts.add(contacts);
}
pCur.close();
}
}
}
if (cur != null) {
cur.close();
}
With this way, all contact are retrieved to a list (Local storage, Sim, Gmail etc).
I have no problem to remove duplicated contact by name like this:
for (int i = 0; i < mAllContacts.size() - 1; i++) {
if (mAllContacts.get(i).getmContactName().equals(mAllContacts.get(i + 1).getmContactName())) {
Log.d("duplicatedArray", "setAdapter: " + mAllContacts.get(i).getmContactName());
mAllContacts.remove(i+1);
}
}
but it's not a good practice because some times different contacts may have same name,
so i can remove duplicated contact with same method but use:
mAllContacts.get(i + 1).getmPhoneNumber()
And here is the problems comes:
For some reason , the phone number have different format while reading from gmail, local storage , sim.
For ex.
Gmail phone number : +972-54-333-55-88
Local storage phone number : +972-543335588
Sim : +972543335588
How can i solve my problem to remove duplicated values.
And yes , i need to read contact from all places where they appear (gmail, local storage , sim)
Apply regex to change the same phone numbers to a common format e.g.
class Main {
public static void main(String args[]) {
String p1 = "+972-54-333-55-88";
String p2 = "+972-543335588";
String p3 = "+972543335588";
String p4 = "+97(2543)335588";
String p5 = "+97 2543 335588";
String regex = "[^0-9+]";
System.out.println(p1.replaceAll(regex, ""));
System.out.println(p2.replaceAll(regex, ""));
System.out.println(p3.replaceAll(regex, ""));
System.out.println(p4.replaceAll(regex, ""));
System.out.println(p5.replaceAll(regex, ""));
}
}
Output:
+972543335588
+972543335588
+972543335588
+972543335588
+972543335588
Normalize
I think you should normalize these phone numbers before you store them.
So for example all of these:
Gmail phone number : +972-54-333-55-88
Local storage phone number : +972-543335588
Sim : +97254335588
Could just be stored as 97254335588 You can parse these numbers by removing all space, hyphens, and plus signs.
HashSet
It would also be easier to store these in a HashSet so you don't even need to worry about removing duplicates.
A very strange porblem. I'm tring to update contacts name by this rule:
- if a contact's name start with "bit" + space ("bit ") so -> update the contact's name to name.substring(4, name.length()), and that means that the contact name will update without the "bit ".
when I use name.substring from number that lower them 4 (I think until the space in contact's name) its working perfectly. When I use from the 4 character onwards the contact's name multiply. For exmaple, when i use name = name.substring(4, name.length()) while name equal to "bit Lili" its update to:
Lili Lili.
private void updateContact(String name) {
ContentResolver cr = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME + " = ?";
String[] params = new String[] {name};
Cursor phoneCur = managedQuery(ContactsContract.Data.CONTENT_URI,null,where,params,null);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
if ((null == phoneCur)) {//createContact(name, phone);
Toast.makeText(this, "no contact with this name", Toast.LENGTH_SHORT).show();
return;} else {ops.add(ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name.substring(4,name.length()))
.build());
}
phoneCur.close();
try {cr.applyBatch(ContactsContract.AUTHORITY, ops);}
catch (RemoteException e) {e.printStackTrace();}
catch (OperationApplicationException e) {e.printStackTrace();}}
Thanks!
Not a certain answer but it suppose to work the issue you have is with the
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME //This specific part has a problem with the new update function
,name.substring(4,name.length()))
So my fix proposal is to change it to family name and given name change these as you need based on your question you want to remove the given name so it's a fix for that
public static boolean updateContactName(#NonNull Context context, #NonNull String name) {
if (name.length() < 4) return true;
String givenNameKey = ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME;
String familyNameKey = ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME;
String changedName = name.substring(4, name.length());
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
String where = ContactsContract.Data.DISPLAY_NAME + " = ?";
String[] params = new String[]{name};
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(givenNameKey, changedName)
.withValue(familyNameKey, "")
.build());
try {
context.getContentResolver()
.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
I can't delete a conversation from getContentResolver, I don't know in which part am doing mistakes, as I also searched about these but can't help myself and I also tried different sols which were given on stackoverflow but same result & thanks a lot in advance.
Here is the code:
public static boolean deleteSmsofContact(Context context, String number,
boolean deleteLocked)
{
int result;
if (deleteLocked) {
//changes values
String[] selectionArgs=new String[]{number};
String selection= ""+"address=?";
//
result = context.getContentResolver().delete(Uri.parse("content://sms/"),selection,selectionArgs);
// Log.d("UF","WOW "+result+" " +number);
} else {
result = context.getContentResolver().delete(Constants.URI_SMS,
"address=? AND locked=?", new String[] { number, "1" });
}
if (result > 0) {
return true;
}
return false;
}
Here is the method from which I am calling:
boolean result = Utils.deleteSmsofContact(InboxActivity.this, sms.getNumber(), true);
if (result) {
dataList.remove(threadPosition);
iAdapter.notifyDataSetChanged();
Toast.makeText(InboxActivity.this,"Removed",Toast.LENGTH_LONG).show();
}else
{
Toast.makeText(InboxActivity.this,"cant removed",Toast.LENGTH_LONG).show();
}
Well I posted it but did not get the answer so finally I searched a lot on this and the correct answer is until or unless your app is not set a default you can't delete any sms or whole conversation.
Follow this link it will make your app set a default OR you will be able to delete.
I have a problem with my SQLiteOpenHelper class.
I have a database with printer manufacturers and details of any kind of printer.
I try to get all manufacturer from my database with this code and returning them in a arraylist.
// Read database for All printer manufacturers and return a list
public ArrayList<String> getPrManufacturer(){
ArrayList<String> manufacturerList = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(CoDeskContract.Printer.TABLE_NAME,
printerManuProjection, null, null, null, null, null,null);
// If cursor is not null and manufacturer List
// does not contains Manufacturer in the list then add it!
if ((cursor != null) && (cursor.getCount()>0)){
cursor.moveToFirst();
do {
String cursorManufacturer = cursor.getString(0);
//Checking for manufacturer in the list
for(String manufacturerInList:manufacturerList){
if (!manufacturerInList.equals(cursorManufacturer))
manufacturerList.add(cursorManufacturer);
}
}while(cursor.moveToNext());
}
// Return list of manufacturers from database
return manufacturerList;
}
I want every manufacturer to be once in a list.
Somehow i cant to get it to work.
Im still a newbie.
Thanks for any Help.
You can also use the distinct keyword in SQLite (http://www.sqlite.org/lang_select.html). Use SQLiteDatabase.rawQuery(String query, String[] args) for that.
db.rawQuery("SELECT DISTINCT name FROM " + CoDeskContract.Printer.TABLE_NAME,null);
There are two issues:
In the beginning, when your list manufacturerInList is empty then it will not go inside for(String manufacturerInList:manufacturerList){ loop and hence it will never add any entry in the list.
Once you fix your problem 1, still it will not work as if (!manufacturerInList.equals(cursorManufacturer)) checks against each entry in the list and adds the non matching entry in the list possibly multiple times.
To fix the issue, you have two options.
Option1: Use contains as:
if (!manufacturerList.contains(cursorManufacturer)) {
manufacturerList.add(cursorManufacturer);
}
Option2: Use a matchFound boolean flag as:
String cursorManufacturer = cursor.getString(0);
boolean matchFound = false;
//Checking for manufacturer in the list
for(String manufacturerInList:manufacturerList){
if (manufacturerInList.equals(cursorManufacturer)){
matchFound = true;
break;
}
}
if(!matchFound){ // <- doesn't exit in the list
manufacturerList.add(cursorManufacturer);
}
Use ArrayList.contains(Object elem) to check if item is exist in ArrayList or not Change your code as:
// does not contains Manufacturer in the list then add it!
if ((cursor != null) && (cursor.getCount()>0)){
cursor.moveToFirst();
do {
String cursorManufacturer = cursor.getString(0);
//Checking for manufacturer in the list
if (!manufacturerList.contains(cursorManufacturer)) {
manufacturerList.add(cursorManufacturer);
} else {
System.out.println("cursorManufacturernot found");
}
}while(cursor.moveToNext());
}
I need to know if there is a way to say that int type is not found in Java Android.
I'm writing an android application,which is actually written first for Iphone, and have a little issue. At some point I have to check if the int type which returns a method is not found and if it's true do some calculations. The problem is that when I did that in Java as if(Id==0) it's throwing me an exception even if the Id is 0.
this is my method :
private static int localUserIdByServerUserId(int serverUserId, String serverName){
dbHelper = new DataBaseHelper(context, "stampii_sys_tpl.sqlite", null, 1);
dbHelper.getDatabase();
String query = "SELECT id FROM users WHERE objectId = "+serverUserId+" AND serverName = '"+serverName+"' LIMIT 1";
ArrayList<String> result = new ArrayList<String>();
cursor = dbHelper.executeSQLQuery(query);
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
result.add(cursor.getString(cursor.getColumnIndex("id")));
cursor.moveToNext();
}
Log.i("result ","Result : "+result.toString());
Log.i("CURSOR ","Cursor Position : "+cursor.getPosition());
int uuid = Integer.parseInt(result.get(cursor.getColumnIndex("objectId")+1));
Log.w("localUSerByIdServerUserId","LocalUserByIdServerUserId result : "+uuid);
cursor.close();
return uuid;
and here is how I'm using it :
int uuId = rpc.lUserIdByServerUserId(userId,newServerName);
Log.w("uuId","uuId : "+uuId);
if(uuId==0){
// do some calculations
}
Any suggestions ?
lUserIdByServerUserId() could throw an exception when the user is not found.
e.g.
try {
int uuId = rpc.lUserIdByServerUserId(userId,newServerName);
Log.w("uuId","uuId : "+uuId);
}
catch (NotFoundException nfe) {
// do some calculations
}
You will need to modify lUserIdByServerUserId() to throw the exception. You may also need to define your own NotFoundException class if a suitable exception doesn't already exist in the Java libraries.
EDIT:
Alternatively, following on from #mthpvg's answer, you could change lUserIdByServerUserId() to return an Integer type, which can be set to null if not found and tested.
e.g.
Integer uuId = rpc.lUserIdByServerUserId(userId,newServerName);
if (uuId == null) {
// Do some calculations
}