简体   繁体   中英

I can't find the right exception in Try-Catch Block — Android Studio Java

I'm trying to make a button that launches one of two calculators should any of them exist on the device. I'm attempting to use the Android original calculator and Samsung. I'm trying to use the try-catch block method but it doesn't work. it can successfully launch the android calc but it doesn't successfully launch the Samsung one although I know for certain that the popup calc is on the device in question. instead, it goes to the catch with the Toast message. I'm assuming that I just don't have the right exception for the catch. please help me to find the correct code.

try {
                    //this is android original calculator
                    Intent i = new Intent();
                    i.setClassName("com.android.calculator2", "com.android.calculator2.Calculator");
                    startActivity(i);
                }
                catch (UnsupportedOperationException e){
                    //This Launch Samsung calculator
                    Intent i = new Intent();
                    i.setClassName("com.sec.android.app.popupcalculator","com.sec.android.app.popupcalculator.Calculator");
                    startActivity(i);

                } catch (Exception e) {
                    //should no calculator found it will display this massage
                    Toast tt = Toast.makeText(MainActivity.this,"SORRY I CANT OPEN CALCULATOR", Toast.LENGTH_LONG);
                    tt.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                    tt.show();
                }
                break;

With @SonTroung help, I find the solution. I used his suggestion above but when using it, it crashed the app on the device which has no calculator. instead, I added another 'try {' nested in the first catch. that worked.

    try {
        //this is android original calculator
        Intent i = new Intent();
        i.setClassName("com.android.calculator2", "com.android.calculator2.Calculator");
        startActivity(i);
    } catch (ActivityNotFoundException e) {
        //This Launch Samsung calculator
        try {
        Intent i = new Intent();
        i.setClassName("com.sec.android.app.popupcalculator", "com.sec.android.app.popupcalculator.Calculator");
        startActivity(i);
        } catch (Exception e) {
        //should no calculator found it will display this massage
        Toast tt = Toast.makeText(MainActivity.this, "SORRY I CANT OPEN CALCULATOR", Toast.LENGTH_LONG);
        tt.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        tt.show();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM