Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 views
in Technique[技术] by (71.8m points)

android - Reading device phone number throws NULLPointerException

I am trying to read the phone number of the device using the following code. When phone number is not available I read the subcriber id. It works in some phones and throws NULL pointer exception in some devices. The device log shows I am getting NULL pointer exception in the following line

if(MyPhoneNumber.equals(""))

Please let me know how to make it work in all devices.

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

String MyPhoneNumber = tMgr.getLine1Number(); 


if(MyPhoneNumber.equals(""))
             MyPhoneNumber = tMgr.getSubscriberId();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  1. TO avoid null pointer exception, 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();
    
  2. Or we can have a SMS Gateway, and whenever we need the phone number, we can send an sms to the gateway, and then deploy a webservice to return the number, the sms gateway receive the message, however this solution is costly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...