9

The following code works on an emulator, but fails to run on Samsung Galaxy S III.

    final String[] projection = new String[]
    { ContactsContract.Profile.DISPLAY_NAME };
    String name = null;
    final Uri dataUri = Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY);
    final ContentResolver contentResolver = getContentResolver();
    final Cursor c = contentResolver.query(dataUri, projection, null, null, null);

    try
    {
        if (c.moveToFirst())
        {
            name = c.getString(c.getColumnIndex(ContactsContract.Profile.DISPLAY_NAME));
        }
    }
    finally
    {
        c.close();
    }
    System.out.println(name);

Here is the exception:

12-03 20:57:15.751: E/AndroidRuntime(28172): FATAL EXCEPTION: main
12-03 20:57:15.751: E/AndroidRuntime(28172): java.lang.RuntimeException: Unable to start activity ComponentInfo{ht.smca.flashligh/ht.smca.flashligh.MainActivity}: java.lang.NullPointerException
12-03 20:57:15.751: E/AndroidRuntime(28172):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at android.os.Looper.loop(Looper.java:137)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at android.app.ActivityThread.main(ActivityThread.java:4898)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at java.lang.reflect.Method.invokeNative(Native Method)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at java.lang.reflect.Method.invoke(Method.java:511)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at dalvik.system.NativeStart.main(Native Method)
12-03 20:57:15.751: E/AndroidRuntime(28172): Caused by: java.lang.NullPointerException
12-03 20:57:15.751: E/AndroidRuntime(28172):    at com.android.internal.os.LoggingPrintStream.println(LoggingPrintStream.java:298)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at ht.smca.flashligh.MainActivity.onCreate(MainActivity.java:68)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at android.app.Activity.performCreate(Activity.java:5206)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
12-03 20:57:15.751: E/AndroidRuntime(28172):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
12-03 20:57:15.751: E/AndroidRuntime(28172):    ... 11 more

Any Suggestions? I do this for learning purposes, i.e. for a seminar.

Danny Lo
  • 1,553
  • 4
  • 26
  • 48
  • What is line 68 in MainActivity? Please post it. – Joel Fernandes Dec 03 '13 at 20:02
  • You have java null pointer exception so name is null. Put your system.out.println() in the try and you won't have this error. After for getting the name I don't really know – Clad Clad Dec 03 '13 at 20:03
  • Line 68 is println. My goal is to really get the name, but i'm getting null on the real device. As for emulator, this code outputs device holder in console. – Danny Lo Dec 03 '13 at 20:07
  • Make sure you have signed in to your phone's Gmail account. –  Oct 17 '15 at 08:03

5 Answers5

26

This will help you get the owner name stored on the device:

Cursor c = getApplication().getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null); 
c.moveToFirst();
textView.setText(c.getString(c.getColumnIndex("display_name")));
c.close();

Make sure you add this permission in the manifest:

<uses-permission android:name="android.permission.READ_CONTACTS"/>
Leejjon
  • 680
  • 2
  • 7
  • 24
Joel Fernandes
  • 4,776
  • 2
  • 26
  • 48
  • It is actually the same code is posted above. Permissions are set. – Danny Lo Dec 03 '13 at 21:08
  • Since, there would be more than one account in device. Then it will give the display name of very first account. This may be not of google's account in some cases. – Rahul Rastogi Mar 10 '15 at 07:46
  • 3
    An app asking for permission to read ALL contacts is suspicious. This right must not be necessary to read just the name of the owner. – Holger Jakobs Feb 21 '16 at 20:17
  • I don't think android.permission.READ_PROFILE is a legitimate permission. At least it is not there in the MANIFEST class of the Android 25 API. This call works without it as long as you have the READ_CONTACTS permission. – Leejjon Feb 05 '17 at 00:44
5

You have java null pointer exception so name is null. Put your system.out.println() in the try and you won't have this error. After for getting the name I don't really know – Clad

Not my post but your answer : Get Android Device Name (for android device model my bad)

 android.os.Build.MODEL;

Here are two ways to do it :

How can I get the google username on Android?

How can I get the first name (or full name) of the user of the phone?

Community
  • 1
  • 1
Clad Clad
  • 2,653
  • 1
  • 20
  • 32
  • I need to know the name of device holder and not of device itself. The goal is not to get rid off NullPointerException, but to put in my variable really what i want to have. – Danny Lo Dec 03 '13 at 20:08
  • Oh oki anyways your Null come from your initialization like I told you. After I can't really test it right now but maybe something like android.os.Build.USER; may work – Clad Clad Dec 03 '13 at 20:11
3
ContentResolver cr=getContentResolver();
Cursor curser = cr.query(ContactsContract.Profile.CONTENT_URI, null, null, null, null);
if(curser.getCount()>0){
    c.moveToFirst();
    String name=curser.getString(curser.getColumnIndex(
        ContactsContract.Profile.DISPLAY_NAME));
    Toast.makeText(MainActivity.this, "name"+name, Toast.LENGTH_SHORT).show();
}
c.close();
Draken
  • 3,134
  • 13
  • 34
  • 54
  • This works on most devices I have tested, but on my friends Huawei P8 Lite I'm getting this (so make sure you catch this exception for devices that behave like this): android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460) at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136) at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50) at android.database.CursorWrapper.getString(CursorWrapper.java:137) – Leejjon Feb 27 '17 at 15:54
2

This code will give owner full information

Try this code:

public class EmailFetcher{

    static String getName(Context context) {
        Cursor CR = null;
        CR = getOwner(context);
        String id = "", name = "";
        while (CR.moveToNext())
        {
            name = CR.getString(CR.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        }
        return name;
    }


    static String getEmailId(Context context) {
        Cursor CR = null;
        CR = getOwner(context);
        String id = "", email = "";
        while (CR.moveToNext()) {
            id = CR.getString(CR.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID));
            email = CR.getString(CR.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
        }
        return email;
    }


    static Cursor getOwner(Context context) {
        String accountName = null;
        Cursor emailCur = null;
        AccountManager accountManager = AccountManager.get(context);
        Account[] accounts = accountManager.getAccountsByType("com.google");
        if (accounts[0].name != null) {
            accountName = accounts[0].name;
            String where = ContactsContract.CommonDataKinds.Email.DATA + " = ?";
            ArrayList<String> what = new ArrayList<String>();
            what.add(accountName);
            Log.v("Got account", "Account " + accountName);
            for (int i = 1; i < accounts.length; i++) {
                where += " or " + ContactsContract.CommonDataKinds.Email.DATA + " = ?";
                what.add(accounts[i].name);
                Log.v("Got account", "Account " + accounts[i].name);
            }
            String[] whatarr = (String[])what.toArray(new String[what.size()]);
            ContentResolver cr = context.getContentResolver();
            emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, where, whatarr, null);
            if (id != null) {
                // get the phone number
                Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                while (pCur.moveToNext())
                {
                    phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    Log.v("Got contacts", "phone" + phone);
                }
                pCur.close();
            }
        }
        return emailCur;
    }
}
Danny Lo
  • 1,553
  • 4
  • 26
  • 48
Sanjit Majee
  • 129
  • 1
  • 7
0
ContentResolver cr=getContentResolver();
Cursor curser = cr.query(ContactsContract.Profile.CONTENT_URI, null, null, null, null);
if(curser.getCount()>0){
    c.moveToFirst();
    String name=curser.getString(curser.getColumnIndex(
        ContactsContract.Profile.DISPLAY_NAME));
    Toast.makeText(MainActivity.this, "name"+name, Toast.LENGTH_SHORT).show();
}
c.close();

Use the above code for fetching owners name from android device. This basically fetches the name stored in contacts for me user.

Note : There will be an exception like the below for few users

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460) at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136) at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50) at android.database.CursorWrapper.getString(CursorWrapper.java:137)

This exception is not phone specific or user specific. Some users do not set their own contact in the contact list. So for resolving this the user on which the app is started needs to setup in Contacts application the first line that is ME contact. Just enter your name in personal info and card will be generated.

@Leejjon ^^

  • Kindly update your answer. you are using the variable name "cr" (ContentResolver cr) at the start but "c" onward (c.close()). that's why this shows an error in android studio. – Zia Feb 24 '20 at 09:56