app crash and doesn't display Toast message

max0o0 :

I am new to Android development. I want to display a Toast message when the app is not installed. When the app is not installed, for example the Facebook app, the app is crashing. What is the problem in my code?

case R.id.Facebook:
    Intent facebook = getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
    startActivity(facebook);
    if (facebook != null) {
        Toast.makeText(this,"Facebook is not installed ",Toast.LENGTH_LONG);
    }
    return true;

Blundell :

You check for null too late, try this:

case R.id.Facebook:
    Intent facebook = getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
    if (facebook == null) {
        Toast.makeText(this,"Facebook is not installed ",Toast.LENGTH_LONG).show();
    } else {
       startActivity(facebook);
    }
    return true;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324579&siteId=1