erdomester
erdomester

Reputation: 11829

Android nullpointerexception at .indexOf()

I have an app on the market, but in some cases it force closes at the open. According to the crash error there is something wrong with the indexOf command (NullPointerException). Part of the code:

contactName = null;
Context context = getApplicationContext();
Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
myArr.add("");

while (cursor.moveToNext())
{
    contactName  = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
    spaceIndex =  contactName.indexOf(' '); //this is the bad row
    spaceLastIndex =  contactName.lastIndexOf(' ');
    myArr.add(contactName);
}

I test my app on 3 different phones, app is working fine. So I cannot test the code if I change something, as I could not tell the difference. What can cause the error and why does it emerge on only a few phones? (5% of the downloads). A guy contacted me with this error, there are a couple of contacts with special characters in his phone (HTC Legend CM 7.1, and a Vodafone 845 Android 2.1). So I added the same characters to a contact of mine, put blank spaces before the name, tried everything to mess with the contact name, app runs smoothly, so this is not the problem. I am out of the options.

Upvotes: 1

Views: 473

Answers (3)

Arpit Garg
Arpit Garg

Reputation: 8546

contactName  = cursor.getString(cursor.getColumnIndexorThrow(ContactsContract.Contacts.DISPLAY_NAME)); 

Even the display name can be null for some cases... say blank contact..

so check whether the contactName is null or not first before getting index from it.

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359816

contactName is clearly coming back null. You need some sort of null check before you call indexOf on it.

// snip
while (cursor.moveToNext())
{
    contactName  = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
    if (contactName == null) continue;

    spaceIndex =  contactName.indexOf(' ');
    spaceLastIndex =  contactName.lastIndexOf(' ');
    myArr.add(contactName);
}

Upvotes: 1

Kousalik
Kousalik

Reputation: 3137

You should check the contactName, if it isn't null. I think that the column, from which are you trying to get the value, is just empty.

if (contactName != null) { ... and so on

Upvotes: 1

Related Questions