I my application I have written following code in order to extract phone number. When I run it in emulator, everything is fine but when I run it on a real device, application crashes. what is your suggestion? I have added <uses-permission android:name="android.permission.READ_PHONE_STATE"/> in manifest file.
public class TestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView phoneNumber = (TextView)findViewById(R.id.tvPhoneNumber);
phoneNumber.setText(getMy10DigitPhoneNumber());
}
private String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
private String getMy10DigitPhoneNumber(){
String s = getMyPhoneNumber();
return s.substring(2);
}
}
getLine1Number()will return the phone number string if available and null if not available. So you should check for Null Pointer.Also check the length of the string returned by
getLine1Number(). In my phone, i got a""string. In this case,substring()will throwIndexOutOfBoundsException. So check for length ofsalso before calling substring().