android-studioactivitynotfoundexception

How to fix "android.content.ActivityNotFoundException" android-studio 2.3.3


I have a small problem where when I click a certain button within my app, the app completely crashes each time without fail.

I am using android studio 2.3.3 and the app is a barcode scanner, here is the error message I get:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=5010029217902 }

Here is the section of code that is causing the error:

    }
    });
    builder.setNeutralButton("Visit", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
            startActivity(browserIntent);
        }
    });
    builder.setMessage(result.getText());
    AlertDialog alert1 = builder.create();
    alert1.show();

Solution

  • The result when you scan a barcode is often not a valid URL. It is often just a string with several digits. It has no schema or protocol, so it is (very possibly) not defined "what type of resource locator it is". Android's ACTION_VIEW intent is mostly use this information to decide "start which app/activity to open this URL". With a lack of the important information, Android has no idea to open it.

    You may specify some cases for handling the result. For example, if the result begins with "http://" or "https://", directly use your code to handle, but if it is just a string of numbers, display it directly, or append it after some string before it is used for Uri.parse, for example "https://google.com/search?q=", to search this barcode's value as you may wanted, or other things you want to do with that 13 digit result.

    For example, (the code below written in mobile hasn't been tested, just show the idea):

    @Override 
    public void onClick(DialogInterface dialog, int which) {
        Intent browserIntent;
        if (myResult.startsWith("http://") || myResult.startsWith("https://"))
            browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
        else
            browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com/search?q=" + myResult)); 
        startActivity(browserIntent); 
    }