getLine1Number() Returns blank, not null

Pratik Butani picture Pratik Butani · Feb 1, 2014 · Viewed 27.4k times · Source

I want to get Mobile Number of Device. I have used following code reference by Alex Volovoy's This Link

TelephonyManager tMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

Log.d("msg", "Phone : "+mPhoneNumber);

OUTPUT in Logcat:

Without Simcard Phones Returns:

02-01 17:22:45.472: D/msg(29102): Phone : null

With Simcard:

02-01 17:22:45.472: D/msg(29102): Phone : 

I have also taken permission in <uses-permission android:name="android.permission.READ_PHONE_STATE"/> in AndroidManifest.xml

So what should i do? Is there any Mistake?

Answer

Ankit picture Ankit · Feb 1, 2014

To get the phone number from the device , first you have to set your own phone number on the device, just through :

Settings -> About Phone -> Status -> My phone Number

Phone numbers are not available on SIM for each operators, like in india Sim dont have phone numbers in any memory, So WE cant get phone number from these connection. However, some countries, and operators have stored phone numbers on SIM, and we can get those. TO make this to work for all devices we can employ two strategies:

To avoid this problem , we can catch the error and work accordingly. Like:

TelephonyManager tMgr = (TelephonyManager) 
                 ShowMyLocation.this.getSystemService(Context.TELEPHONY_SERVICE);

String MyPhoneNumber = "0000000000";

try 
{
    MyPhoneNumber =tMgr.getLine1Number();
}
catch(NullPointerException ex)
{
}

if(MyPhoneNumber.equals("")){
    MyPhoneNumber = tMgr.getSubscriberId();
}