Reputation: 155
I want to declare TelephonyManager
in MainActivity
not OnCreate
. In OnCreate
there is no problem but when I use in MainActivity
it gives a null pointer exception.
Structure of my code is needed to declare TelephonyManager
in MainActivity
.
public class MainActivity extends Activity {
TelephonyManager mngr = (TelephonyManager) getApplicationContext().getSystemService(getApplicationContext().TELEPHONY_SERVICE);//Error line here.
String imei = mngr.getDeviceId();
protected void onCreate(Bundle savedInstanceState) {
//My jobs
}
}
How to solve this problem?
Upvotes: 2
Views: 980
Reputation: 21
Copy this line into your onCreate
method:
TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
You are in a class that extends Activity
(Activity
extends Context
), so you can call Context
's methods directly from your class.
Upvotes: 2