0

in my app I have a button that when you press it opens an app. It works, but if people don't have the app installed, it crashes the app. So I wanted to make a dialog that says "app not found" instead of crashing the app. Here's my button intent:

public void myClickHandler(View v){
    Intent i = new Intent(Intent.ACTION_MAIN);
    i.setComponent(new ComponentName("com.mojang.minecraftpe",     
"com.mojang.minecraftpe.MainActivity"));
    i.addCategory(Intent.CATEGORY_LAUNCHER);
    startActivity(i);}

And heres my dialog code:

new AlertDialog.Builder(this)
    .setTitle("MCPE not installed!")
    .setMessage("For this feature to work you need MCPE installed to your   
device.     You can use a download link above to get it")
    .setPositiveButton(R.string.dialog, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // continue with delete
        }
     })
    .setIcon(android.R.drawable.ic_dialog_alert)
     .show();
}

2 Answers2

0

Use try/catch blocks and call show() method of your dialog inside catch as follows

public void myClickHandler(View v){
    try{
        Intent i = new Intent(Intent.ACTION_MAIN);
        i.setComponent(new ComponentName("com.mojang.minecraftpe",     
                "com.mojang.minecraftpe.MainActivity"));
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        startActivity(i);
    }catch(ActivityNotFoundException e){
        new AlertDialog.Builder(this)
        .setTitle("MCPE not installed!")
        .setMessage("For this feature to work you need MCPE installed to your   
                device.     You can use a download link above to get it")
                .setPositiveButton(R.string.dialog, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { 
                        // continue with delete
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }
}

or, better yet, check whether the application is installed first.

How can I learn whether a particular package exists on my Android device?

Community
  • 1
  • 1
yildirimyigit
  • 3,013
  • 4
  • 25
  • 35
0
try {
   ...
   startActivity(i);
} catch (ActivityNotFoundException e) {
   showDialog();
}
ucdevs
  • 49
  • 8