Mischaila
Mischaila

Reputation: 39

android telephone number

I want to display my telephone number when I open the application, but I get a exception saying

The application Telephone has ()stopped unexpectedly. Please try again.

I have already added Read_Phone_State permission in manifest file.

public class Telephone extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        View v = new View(this);
        v.setTag("The Number is : " + getMyTenDigitsNumber());
        setContentView(v);

    }

    private String getTelephone() {
        TelephonyManager tm;
        tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getLine1Number();

    }

    private String getMyTenDigitsNumber() {
        String s = getTelephone();
        return s.substring(3);
    }
}

Upvotes: 2

Views: 478

Answers (2)

Raghav Sood
Raghav Sood

Reputation: 82563

It's possible that getLine1Number() returns null, and therefore your substring operation throws an NPE. getLine1Number() returns null when the number is unavailable, like when there is no SIM card inserted, or the number is not stored on the SIM card. You can check if the number is available by going to Settings -> About phone -> Status and checking if your number is displayed in the My phone number field.

Upvotes: 0

Chris
Chris

Reputation: 23171

It's likely that getLine1Number is returning null so your subsequent substring operation throws a NullPointerException (you should be able to verify via logcat). According to the documentation for the method, it can return null if the number is unavailable. It is possible that your provider doesn't store the phone number on the SIM so, in that case, the number may not be available to that method.

Upvotes: 1

Related Questions