1

The mPhoneNumber variable is coming back null. I have been debugging this thing for a week and I am extremely stuck. Why does getLine1Number return null?

try
{
    TelephonyManager tMgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
    if (tMgr != null)
    {
        if (checkSelfPermission(android.Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED)
        {
            if (checkSelfPermission(android.Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)
            {
                // TODO: Consider calling
                // Activity#requestPermissions
                // here to request the missing permissions, and then overriding
                // public void onRequestPermissionsResult(int requestCode, String[] permissions,
                // int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                return;
            }
        }
        String mPhoneNumber = tMgr.getLine1Number();
        // Log.v("PHONE: ", mPhoneNumber);
    }
    else
    {
        //Log.v("PHONE NO: ", "NO");
    }   
}
catch(Exception e)
{
    // TODO: Handle exception
}
MechMK1
  • 3,278
  • 7
  • 37
  • 55
Mike
  • 15
  • 4
  • 1
    In the 4th line you are checking if you have the permission to read the phone state. If so you return. If not you try to read the phone number. The String mPhoneNumber = tMgr.getLine1Number(); line must be inside the brackets of checking android.Manifest.permission.READ_PHONE_STATE. Or the == must be changed to != – Gilian Joosen Dec 30 '17 at 16:13
  • In addition to that problem, bear in mind that [it is documented to sometimes return `null`](https://developer.android.com/reference/android/telephony/TelephonyManager.html#getLine1Number()). – CommonsWare Dec 30 '17 at 16:17
  • Are you sure `mPhoneNumber` here is `null` and not some variable with the same name somewhere else? You said you got an NPE, but this code wouldn't throw an NPE (I removed this part of the question, otherwise it will probably be closed as a duplicate.) – NickL Dec 30 '17 at 16:17

1 Answers1

2

Network providers do not always store the phone numbers (msisdn) on SIM card. Therefore, getting the phone number strongly depends on what mobile operator you use.

Some operators put the phone number into the header (for web browser users) after their gateways are passed; some of them places the msisdn directly to the SIM card; and some of them provides only "token"s to identify their users.

This can be a reason of why you get "null" value when you try to get your number.

Please check that too

anL
  • 1,073
  • 1
  • 11
  • 31