0

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();
E_net4
  • 27,810
  • 13
  • 101
  • 139
Moh Nab
  • 19
  • 1
  • 6
  • Where the error occurs? – Daniel Reyhanian Feb 11 '19 at 15:59
  • Hey Daniel, the error occurs when I click the "visit" button in the app. It is supposed to get information from the barcode scan and put it into an internet search, hence "visit". When i click this button, the above error message is what i get... hope this answered your question, if not, let me know what other details i can give you – Moh Nab Feb 11 '19 at 16:01
  • I meant, in what line of the code? – Daniel Reyhanian Feb 11 '19 at 16:02
  • Plus what is myResult? Where is the value of it? – Daniel Reyhanian Feb 11 '19 at 16:02
  • I think the error occurs here: Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult)); – Moh Nab Feb 11 '19 at 16:04
  • myResult is made here: public void handleResult(Result result) { final String myResult = result.getText(); Log.d("QRCodeScanner", result.getText()); Log.d("QRCodeScanner", result.getBarcodeFormat().toString()); – Moh Nab Feb 11 '19 at 16:05
  • Please check that the specific part of code is familiar with the value of myResult. – Daniel Reyhanian Feb 11 '19 at 16:06
  • i dont quite understand what you mean by “familiar”، can you elaborate? – Moh Nab Feb 11 '19 at 16:07
  • Hmm, the code seems just fine, it just looks like the system has no idea what value myResult holds, because this variable exists only in other function or part of code. Why not passing myResult to onClick? `public void onClick(DialogInterface dialog, int which, string myResult)` – Daniel Reyhanian Feb 11 '19 at 16:09
  • Hey, i tried to do this to my code, but i get red underline under "string" saying " cannot resolve symbol "string" " – Moh Nab Feb 11 '19 at 16:13
  • You set `myResult` to `String` not to `string`. Change one of them. – Daniel Reyhanian Feb 11 '19 at 16:14
  • Read about the difference [here](https://stackoverflow.com/questions/7074/what-is-the-difference-between-string-and-string-in-c). – Daniel Reyhanian Feb 11 '19 at 16:15
  • I changed it to String and got these 3 errors---->>> Error:(147, 81) error: is not abstract and does not override abstract method onClick(DialogInterface,int) in OnClickListener ++++++++++++ Error:(148, 13) error: method does not override or implement a method from a supertype +++++++++++++++++++++ Error:Execution failed for task ':app:compileDebugJavaWithJavac'. > Compilation failed; see the compiler error output for details. – Moh Nab Feb 11 '19 at 16:19
  • Got it. About. Try creating a static variable `static string myTurn` and then you can use it freely. – Daniel Reyhanian Feb 11 '19 at 16:21
  • it says "modifier static is not allowed here" – Moh Nab Feb 11 '19 at 16:26
  • Could you paste the whole code? – Daniel Reyhanian Feb 11 '19 at 16:28
  • yes, i will update the post itself to feature the full source-code: i will enter it now – Moh Nab Feb 11 '19 at 16:33
  • Looks like you are trying to open a webpage URL. For that you need a web browser app like google chrome. Do you have any browser installed? – Saikrishna Rajaraman Feb 11 '19 at 16:37
  • @SaikrishnaRajaraman yes i have google chrome installed on the android device i am testing the program on – Moh Nab Feb 11 '19 at 16:38
  • @DanielReyhanian i have pasted the source-code as an answer – Moh Nab Feb 11 '19 at 16:38
  • 1
    Can u post the value of myResult? Doesn't seem to be an URL i guess – Saikrishna Rajaraman Feb 11 '19 at 16:42
  • @SaikrishnaRajaraman you’re right, the value isnt a URL, its the result of scanning the barcode so it is a 13-digit number – Moh Nab Feb 11 '19 at 16:44

3 Answers3

0
package com.example.priyanka.qrbarcodescanner;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.content.ClipboardManager;


import com.google.zxing.Result;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

import static android.Manifest.permission.CAMERA;

public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {

    private static final int REQUEST_CAMERA = 1;
    private ZXingScannerView scannerView;
    private static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        scannerView = new ZXingScannerView(this);
        setContentView(scannerView);
        int currentApiVersion = Build.VERSION.SDK_INT;

        if(currentApiVersion >=  Build.VERSION_CODES.M)
        {
            if(checkPermission())
            {
                Toast.makeText(getApplicationContext(), "Permission already granted!", Toast.LENGTH_LONG).show();
            }
            else
            {
                requestPermission();
            }
        }
    }

    private boolean checkPermission()
    {
        return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED);
    }

    private void requestPermission()
    {
        ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
    }

    @Override
    public void onResume() {
        super.onResume();

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
            if (checkPermission()) {
                if(scannerView == null) {
                    scannerView = new ZXingScannerView(this);
                    setContentView(scannerView);
                }
                scannerView.setResultHandler(this);
                scannerView.startCamera();
            } else {
                requestPermission();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        scannerView.stopCamera();
    }

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CAMERA:
                if (grantResults.length > 0) {

                    boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if (cameraAccepted){
                        Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (shouldShowRequestPermissionRationale(CAMERA)) {
                                showMessageOKCancel("You need to allow access to both the permissions",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                    requestPermissions(new String[]{CAMERA},
                                                            REQUEST_CAMERA);
                                                }
                                            }
                                        });
                                return;
                            }
                        }
                    }
                }
                break;
        }
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new android.support.v7.app.AlertDialog.Builder(MainActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void handleResult(Result result) {
        Log.d("QRCodeScanner", result.getText());
        Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
        final static String myResult = result.getText();


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Scan Result");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                scannerView.resumeCameraPreview(MainActivity.this);

            }
        });
        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();
    }
}
Moh Nab
  • 19
  • 1
  • 6
0
package com.example.priyanka.qrbarcodescanner;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import android.content.ClipboardManager;


import com.google.zxing.Result;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

import static android.Manifest.permission.CAMERA;

public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {

    private static String myResult;
    private static final int REQUEST_CAMERA = 1;
    private ZXingScannerView scannerView;
    private static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        scannerView = new ZXingScannerView(this);
        setContentView(scannerView);
        int currentApiVersion = Build.VERSION.SDK_INT;

        if(currentApiVersion >=  Build.VERSION_CODES.M)
        {
            if(checkPermission())
            {
                Toast.makeText(getApplicationContext(), "Permission already granted!", Toast.LENGTH_LONG).show();
            }
            else
            {
                requestPermission();
            }
        }
    }

    private boolean checkPermission()
    {
        return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED);
    }

    private void requestPermission()
    {
        ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
    }

    @Override
    public void onResume() {
        super.onResume();

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
            if (checkPermission()) {
                if(scannerView == null) {
                    scannerView = new ZXingScannerView(this);
                    setContentView(scannerView);
                }
                scannerView.setResultHandler(this);
                scannerView.startCamera();
            } else {
                requestPermission();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        scannerView.stopCamera();
    }

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CAMERA:
                if (grantResults.length > 0) {

                    boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if (cameraAccepted){
                        Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (shouldShowRequestPermissionRationale(CAMERA)) {
                                showMessageOKCancel("You need to allow access to both the permissions",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                    requestPermissions(new String[]{CAMERA},
                                                            REQUEST_CAMERA);
                                                }
                                            }
                                        });
                                return;
                            }
                        }
                    }
                }
                break;
        }
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new android.support.v7.app.AlertDialog.Builder(MainActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void handleResult(Result result) {
        Log.d("QRCodeScanner", result.getText());
        Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
        myResult = result.getText();


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Scan Result");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                scannerView.resumeCameraPreview(MainActivity.this);

            }
        });
        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();
    }
}
Daniel Reyhanian
  • 579
  • 4
  • 26
  • Try copy pasting it into your code. If it's not working then the problem is not with the URI. – Daniel Reyhanian Feb 11 '19 at 16:44
  • Hey, i tried pasting this into my code, and the "myResult = result.getText ();" gives me an error. It says: incompatible types. Required: string Found: java.lang.String – Moh Nab Feb 11 '19 at 16:48
  • sorry, Edied. Try it now. – Daniel Reyhanian Feb 11 '19 at 16:53
  • Just thought i'd let you know, the "visit" button works normally if the QR code leads to a url link such as www.youtube.com, however if i am scanning a barcode that returns a 13 digit number as the value, the program crashes when i click "visit". Does this make sense? and can it be fixed? – Moh Nab Feb 11 '19 at 16:57
  • You should have said that earilier, you can keep the code as it was if it's working. Try adding `try` and `catch`. Read more [here](https://beginnersbook.com/2013/04/try-catch-in-java/). – Daniel Reyhanian Feb 11 '19 at 17:05
0

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); 
}
Geno Chen
  • 4,916
  • 6
  • 21
  • 39
  • Yes! this is exactly what i wanted to do... a google search containing the numbers that got returned from the barcode. do you mind showing me how to do this? i am very new i have no idea how to do it. thanks so much! – Moh Nab Feb 11 '19 at 17:02
  • @MohNab See my updated answer. It is easier than you think. – Geno Chen Feb 11 '19 at 17:08
  • I have added this to my code and it works absolutely perfectly! Thank you so much for your patience, help, and quick replies! :D – Moh Nab Feb 11 '19 at 17:11
  • @MohNab If someone's answer successfully helps you, you can upvote and accept that answer, which helps others to solve their similar questions more quickly, for example mine :-) – Geno Chen Feb 11 '19 at 17:14
  • I clicked the green tick, was that how to accept the answer? – Moh Nab Feb 11 '19 at 17:16
  • @MohNab Yes :-) – Geno Chen Feb 11 '19 at 17:16