0

Am developing an android app to read contacts(name and number) from phone and save it in SQLite database(somewhat like syncing contacts to my app, not actually). Already I read and saved contacts that were in the phone.

Now I want to add new contacts that were added to the phone after the app was installed. So what am planning to do is to read all contacts from the phone and compare it with already saved contacts in the database. It is done by comparing numbers(by checking whether read number and number in database are same). If a read number from phone is not found in the database, I want to save that number and its particular contact name into database. The following code is to do it.

public int checkContacts(String name, String number) { // name and number are read from phone String query = "select name,number from contacts"; cur = db1.rawQuery(query, null); // cur is object of Cursor while(cur.moveToNext()) { array.add(cur.getString(1)); // array is object of ArrayList<String> if( !(number.equals(array))) { insertContacts(name, number); // function to insert to database count++; // count is used to get the number of contacts saved } } return count; } 

Am developing this app using Eclipse and an Android Emulator. After executing this code some 20000+ contacts got saved to my database. Actually there were only 11 contacts in my emulator.

Why this much contacts got added to my database and how can I add only newly added contacts to database ?

2 Answers 2

1

Try to check for the value in your array list using contains method of ArrayList as below: contains method Searches the ArrayList for the specified object.

 if(!array.contains(number)) 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for that. I replaced my if condition with yours. Now I can save newly added contact. But the newly added contact is getting saved cur.getCount() times.
What are you trying to say i am not getting you?
Your code solved my issue somewhat. But there is still a little problem. There was already 11 contacts saved in the database. When I executed the code after editing as you said, the newly added contact got saved to the database 11 times.
Anyway thanks for your help. I made a little edits and now its working.
0
(number.equals(array)) => always return false 

1 Comment

if you are checking only based on number, remove name from query. and check if cursor.getCount() == 0. Then only insert. One more thing, you should try these things yourself to learn fast than asking on forum.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.