Reputation: 93
i want to write simple application in android to fetch sim card number,i use this code:
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
write up code in Fragment into this block:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
In the this line:
mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
I get error this part : mAppContext.getSystemService
.
How can i solve that problem?
thanks for you for pay attention to my problem.
Upvotes: 0
Views: 501
Reputation: 12167
For some reasons, this API will get an empty one if the device didn't have the SIM number storing support. If so, we have to ask the user to input the number by hand.
TelephonyManager telephonyManager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
String phone = telephonyManager.getLine1Number();
if (phone != null && phone.isEmpty()) {
// TODO: ask the user to input his/her telephone number
}
Upvotes: 0
Reputation: 15799
Please check AndroidManifest.xml whether you have declare following permission or not.
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
If not then add it after that change your mAppContext
to getActivity()
to run your code.
Upvotes: 0
Reputation: 93
have you provided the permission READ_PHONE_STATE in the manifest.
Upvotes: 0
Reputation: 3926
it gives you all contacts:
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null,
null);
Cursor phoneCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
Phone_CONTACT_ID + " = ?", new String[] { contact_id },
null);
String phoneNumber = phoneCursor.getString(phoneCursor
.getColumnIndex(NUMBER));
create loop for cursor and get all contacts.
Upvotes: 0
Reputation: 547
Method you are using is the only one part of the SDK to do this, and only works on devices where the number is stored on the SIM card, which only some carriers do. For all other carriers, you will have to ask the user to enter the phone number manually, as the number is simply not stored anywhere on the device from where you can retrieve it.
Upvotes: 0
Reputation: 47817
get context in Fragment
by using getActivity()
TelephonyManager tMgr = (TelephonyManager)getActivity().getSystemService(Context.TELEPHONY_SERVICE);
Upvotes: 2