I am stuck with a problem in which some contacts contain a country code while others don't.
I have code for fetching contact numbers which are being saved in list. The list looks like this:
[9999999999, 91-8888888888, 91-0000000000, 1111111111]
Now, I want to remove country code from those numbers which have it. I can't figure out a way to check this.
Here is my code for fetching contacts:
ContentResolver cr = getApplicationContext().getContentResolver(); //Activity/Application android.content.Context
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
if(cursor.moveToFirst())
{
do
{
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if(Integer.parseInt(cursor.getString(cursor.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 contactName = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY));
String contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
allContacts.add(contactName);
contactNumber = contactNumber.replaceAll("\\s+","");
allnumbers.add(contactNumber);
break;
}
pCur.close();
}
} while (cursor.moveToNext()) ;
}
}
Here, allnumbers contains the number (where some have country code with them and others don't). How can I remove the country code from those who have it?
Any help or keywords to search will be appreciated, thanks.
If you want to remove the first occurance of a string containing '91-', you could simply use the replaceFirst() method. So your code will end up like this:
contactNumber.replaceAll("\\s+","").replaceFirst("91-","");
If you want to check if a string starts with '91-', you could use this:
if (contactNumber.startsWith("91-")) {
}
In your sample with array of numbers you have dash(-) between countrycode. So you can just use indexOf to determine if number has country code. You can do the same thing using regexp([\d]+-[\d]+)
Also you can count degits. Usually numbers without country codes have only 10 digits. It depends on your situation
Just try
contactNumber = contactNumber.replace("+91", "");
Hope this helps...
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.
I need some guidance on my current obstacle with this application. If you can point me in the right direction will help. Basically I have twitter like application with a sql database storing the "tweets" and the users data.The user's nickname always start with a "#". Now everything is working but i need to add the functionality that if I send a twit and "mentioned" a user, meaning I add #nickname , then that person I mentioned should see it on his messages. I think I can figure it out, but i'm just confused on how to get started, specifically when I'm getting the "tweet" how can I find a "#" and return the word that contains the "#" ? The next step should probably be to see if that nickname exists and find the userID by the nickname and update their messages? Please help me out.
This is what I'm trying.. not working..
HttpSession session = request.getSession();
String tweet = request.getParameter("tweet");
ArrayList<User> x= new ArrayList<User>();
for(int i = 0; i < x.size(); i++){
String alias = x.get(i).getAlias();
if(tweet.contains(alias)){
try {
int uid= getUseridByNickName(alias);
Twit t = new Twit();
t.setMentionedUserID(uid);
} catch (SQLException ex) {
Logger.getLogger(TwitServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
To get the username of the mentioned users you could simply use the indexOf method:
String s = "#user1 #user2 some text";
ArrayList<String> users = new ArrayList<>();
int index = s.indexOf("#");
while(index != -1) {
users.add(s.substring(index + 1, s.indexOf(" ", index)));
index = s.indexOf("#", index + 1);
}
users.stream().forEach(System.out::println);
Note that this method will work only if the username is followed by a space, otherwise the username will also contain the text between the "#" and the first space it founds (e.g. the tweet "#user1, some text" will return "user1,")
I created a small activity that displays all contacts with phone numbers in my phone. However, there are duplicates for contacts that have whatsapp installed. For example, if John is in my contact list and he has a whatsapp account as well, the list would look like this:
...
Jake
John
John
JP
...
This is my code for assigning the cursor to the the adapter which links to a listview.
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
final Cursor cursor = getContentResolver().query(uri, null, null, null, sortOrder);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1};
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, cursor, from, to, 0);
EDIT
With this code, I confirmed that the duplicates have 0 value for the ContactsContract.CommonDataKinds.Phone.TYPE which means it is a custom contact (Whatsapp). The rest are 2 which means it is a normal contact.
I need to figure out a query where it doesn't use any contacts where ContactsContract.CommonDataKinds.Phone.TYPE == 0
I know it might be a bit late. However I was having the same issue.
ContactsContract.CommonDataKinds.Phone.TYPE as per the android documentation refers not to whether it is a custom contact but to what type of contact it is i.e. Mobile(2), Home(1) or Work(3). Whatsapp contacts will be a 2 - mobile.
I used the following function to remove the duplicates (not sure if there is a better way):
private boolean checkDuplicate(String position) {
LinkedHashMap<String, Integer> map;
Integer testNull;
map=new LinkedHashMap<>();
testNull=map.get(position);
if(testNull==null) {
testNull=1;
map.put(position, testNull);
return false;
}
else {
testNull=testNull+1;
if(testNull==2) {
return true;
}
else {
map.put(position, testNull);
return false;
}
}
}
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 am working on a project with 2 other people, and as you can probably guess its a bit tought working with someone elses code. The app we are developing gets info from the internet, each item consisting of a title, link, post, and date. This info is read into a cursor and then output all in a single string buffer. This is obviously useless if you want to display the info neatly in an emulator window. I was hoping someone could help me understand how to work with the info to make it easy to use (i.e. each entry in one TextView, with all entries in a listview).
private void showEvents() {
SQLiteDatabase db = post.getWritableDatabase();
Cursor cursor= db.rawQuery("SELECT "+TITLE+", "+LINK+", "+POST+", "+DATE+" FROM "+TABLE_NAME+" "+"ORDER BY "+DATE+" DESC;",null);
startManagingCursor(cursor);
TextView tv = new TextView(this);
// Stuff them all into a big string
StringBuilder builder = new StringBuilder("");
while (cursor.moveToNext()) {
String title = cursor.getString(0);
String link = cursor.getString(1);
String post = cursor.getString(2);
String date= cursor.getString(3);
builder.append(title).append(": " );
builder.append(link).append(": " );
builder.append(post).append(": " );
builder.append(date).append("\n" );
}
// Display on the screen
tv.setText(builder);
this.setContentView(tv);
}
This code basically just outputs everything, unformmatted onto the screen. I've been trying to figure how to enter the while loop to capture each entity (which is 1 of title, link,post,date) and go from there.
Any advice is appreciated.
I'd suggest you read a book. One that will cover these topics is "Android in Practice", from Manning Publications.
There are several important required elements for this, but the key concept is an "Adapter", which connects views with data. You would end up defining a POJO to represent the data in each record, and your custom Adapter maps from that POJO into view fields.
Every time you enter this while loop, you are reading another line (because of the moveToNext())
while (cursor.moveToNext()) {
String title = cursor.getString(0);
String link = cursor.getString(1);
String post = cursor.getString(2);
String date= cursor.getString(3);
builder.append(title).append(": " );
builder.append(link).append(": " );
builder.append(post).append(": " );
builder.append(date).append("\n" );
}