How Do I Resolve Nullpointerexception When Calling Methods?
Solution 1:
If your 2 classes are 2 separated Activities, your case will cause Null Pointer Exception, because when 2nd activity is running, 1st activity is stopped (terminated) -> this is Android OS mechanism, you can not change.
Solutions for your case:
(1) Activity 1 is parent of others, this case is suitable for Application class or TabHost (complicated).
(2) Create static method like @Zapl's answer; But it's still not quite nice because this static method should be in common use instead of inside Class 1 -> modify: Create a common Class like following:
This is utility class:
publicclassGlobalUtil
{
publicstaticvoidstartUrlActivity(Context context, String url) {
try {
Intent callIntent = newIntent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(url));
context.startActivity(callIntent); //<-- pass current activity or context
} catch (ActivityNotFoundException activityException) {
Log.e("dialing-example", "Call failed", activityException);
}
}
}
And inside any other activity class you can call it:
GlobalUtil.startUrlActivity(this, "tel:1234567890"/*+phonenumber0*/");
OR
GlobalUtil.startUrlActivity(getBaseContext().getApplicationContext(), "your_url");
Solution 2:
This will work if call0() is a method of the same activity class.
publicvoidcall0() {
try {
Intent callIntent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:1234567890"));
startActivity(callIntent);
} catch (ActivityNotFoundException activityException) {
Log.e("dialing-example", "Call failed", activityException);
}
}
And dont forget to add this in your manifest file:
<uses-permissionandroid:name="android.permission.CALL_PHONE"></uses-permission>
And I dont think this a good thing:
BottlesActivityinst=newBottlesActivity();
inst.call0();
Instead when the button is clicked, call call0() like below:
publicvoidonClick(View v) {
switch(v.getId()){
case R.id.idButton:
call0();
break;
}
}
Solution 3:
You can't create an Activity
yourself. You could use a static
method in another Activity class.
from any Activity:
BottlesActivity.call0(this);
in BottlesActivity
publicstaticvoidcall0(Context context) {
try {
IntentcallIntent=newIntent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:1234567890"/*+phonenumber0*/));
context.startActivity(callIntent); //<--This line causes nullpointerexception
} catch (ActivityNotFoundException activityException) {
Log.e("dialing-example", "Call failed", activityException);
}
}
Post a Comment for "How Do I Resolve Nullpointerexception When Calling Methods?"