jhansireddy / AndroidScannerDemo

ScanLibrary is an android document scanning library built on top of OpenCV, using the app you will be able to select the exact edges and crop the document accordingly from the selected 4 edges and change the perspective transformation of the cropped image.
MIT License
1.07k stars 472 forks source link

Nothing happens after click image #112

Open ajinkya976 opened 4 years ago

ajinkya976 commented 4 years ago

Hi Everyone,

please find my project here https://drive.google.com/open?id=1pKTq0QwxuN1jy9Q1eFSQyr-TUEHFKHtQ

i am using this library in my project i am able to take picture from camera but nothing happens after that. when i click on select button after clicking image, crop part is not coming. i am getting below error.

W/System.err: java.lang.NullPointerException: Attempt to get length of null array
        at com.reminder.testapplication.PickImageFragment.clearTempImages(PickImageFragment.java:67)
        at com.reminder.testapplication.PickImageFragment.createImageFile(PickImageFragment.java:133)
        at com.reminder.testapplication.PickImageFragment.openCamera(PickImageFragment.java:117)
        at com.reminder.testapplication.PickImageFragment.handleIntentPreference(PickImageFragment.java:77)
        at com.reminder.testapplication.PickImageFragment.init(PickImageFragment.java:58)
        at com.reminder.testapplication.PickImageFragment.onCreateView(PickImageFragment.java:48)
        at android.app.Fragment.performCreateView(Fragment.java:2534)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1303)
        at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2431)
        at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2210)
        at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2166)
W/System.err:     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2067)
        at android.app.FragmentManagerImpl.dispatchMoveToState(FragmentManager.java:3057)
        at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3004)
        at android.app.FragmentController.dispatchActivityCreated(FragmentController.java:184)
        at android.app.Activity.performCreate(Activity.java:7822)
        at android.app.Activity.performCreate(Activity.java:7804)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1318)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3349)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3513)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2109)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
D/: openCamera: isDirectoryCreated: false
V/ViewRootImpl: The specified message queue synchronization  barrier token has not been posted or has already been removed
D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@664c4c[ScanActivity]
W/Choreographer: Already have a pending vsync event.  There should only be one at a time.
D/OpenGLRenderer: endAllActiveAnimators on 0x729c177600 (RippleDrawable) with handle 0x72f658d060
E/ContentProviderNative: onTransact error from {P:7122;U:10040}
zakblacki commented 4 years ago

Search scanlibrary in github you will find other project using the same depo working

ajinkya976 commented 4 years ago

actually projects i dont want i have imported everything properly also i saw one more issue is open with above error but no one replied to it as well

mauclores commented 4 years ago

Was this solved?

mauclores commented 4 years ago

In my case this happens only when the device is running Android 10 and the targetSdkVersion in manifest file is 29.

The issue is related to external storage directory accessibility as described in the documentation: https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory(). The related code is in ScanConstants.java: public final static String IMAGE_PATH = Environment .getExternalStorageDirectory().getPath() + "/scanSample";

To solve this, you can:

  1. Set the targetSdkVersion to less than 29 (not recommended); or
  2. Create the image file elsewhere (tested with getExternalCacheDir())
ajinkya976 commented 4 years ago

Thanks i will check this. can you please let me know how to do second option ? i am having android 10

amila4d commented 4 years ago

public class ScanConstants {

public final static String IMAGE_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath() + "/scanSample";

}

ajinkya976 commented 4 years ago

Hi,

i have tried with above solutions but i am getting below error. i am getting this error whenever i click image in camera.

E/ContentProviderNative: onTransact error from {P:32644;U:10040}

shahbikash commented 4 years ago

@ajinkya976 hey there, did you provide the permission to the installed app on your device, like going to app permissions and providing access to camera and Storage, if not do it and try again. It should work :)

ajinkya976 commented 4 years ago

@shahbikash yes i have given permission but still gets below error when i click image and nothing happens when click check button.

E/ContentProviderNative: onTransact error from {P:764;U:10040}

Screenshot_20200618-122423

image

vamsee9 commented 4 years ago

public class ScanConstants {

public final static String IMAGE_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath() + "/scanSample";

}

where should we add this? in Utils.java or MainActivity.java ?

amila4d commented 4 years ago

Inside library. Just search class name in library project

On Thu, Jul 9, 2020 at 6:40 PM, 4И0И5UЯF notifications@github.com wrote:

public class ScanConstants {

public final static String IMAGE_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath()

  • "/scanSample";

}

where should we add this? in Utils.java or MainActivity.java ?

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/jhansireddy/AndroidScannerDemo/issues/112#issuecomment-656117613, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACC6GHNW3NLGXFMZ7C6M6BTR2W6UNANCNFSM4KOS3F4A .

vamsee9 commented 4 years ago

Inside library. Just search class name in library project On Thu, Jul 9, 2020 at 6:40 PM, 4И0И5UЯF @.***> wrote: public class ScanConstants { public final static String IMAGE_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath() + "/scanSample"; } where should we add this? in Utils.java or MainActivity.java ? — You are receiving this because you commented. Reply to this email directly, view it on GitHub <#112 (comment)>, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACC6GHNW3NLGXFMZ7C6M6BTR2W6UNANCNFSM4KOS3F4A .

yeah tried, nothing happened the same being able to take a picture from the camera but nothing happens after that. when I click on the select button after clicking the image, crop part is not coming

vamsee9 commented 4 years ago

@shahbikash yes i have given permission but still gets below error when i click image and nothing happens when click check button.

E/ContentProviderNative: onTransact error from {P:764;U:10040}

Screenshot_20200618-122423

image

Did you solve error ?

ajinkya976 commented 4 years ago

no. i am also getting same error not found any solution till now for this.

vamsee9 commented 4 years ago

In my case this happens only when the device is running Android 10 and the targetSdkVersion in manifest file is 29.

The issue is related to external storage directory accessibility as described in the documentation: https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory(). The related code is in ScanConstants.java: public final static String IMAGE_PATH = Environment .getExternalStorageDirectory().getPath() + "/scanSample";

To solve this, you can:

  1. Set the targetSdkVersion to less than 29 (not recommended); or
  2. Create the image file elsewhere (tested with getExternalCacheDir())

I have tried 2 option tested with getDownloadCacheDir() when I click on the camera it force closes

ajinkya976 commented 4 years ago

yes i have also tried above options but it not worked for me

mauclores commented 4 years ago

Hello. Sorry I could not check code right now but could you try the following?

  1. In PickImageFragment.java, create a variable imagePath. private String imagePath = "";

  2. Under init(), initialize imagePath imagePath = getActivity().getApplicationContext().getExternalCacheDir().getPath() + "/scanSample";

  3. Replace all instances of ScanConstants.IMAGE_PATH to imagePath. (I think there are 2 instances).

The idea is that the image file is stored in the application's cache directory. It was tested only using the default camera(Google camera) installed on device. 3rd Party cameras not yet tested.

vamsee9 commented 4 years ago

Thanks sir I will check out with it

ajinkya976 commented 4 years ago

Hello. Sorry I could not check code right now but could you try the following?

  1. In PickImageFragment.java, create a variable imagePath. private String imagePath = "";
  2. Under init(), initialize imagePath imagePath = getActivity().getApplicationContext().getExternalCacheDir().getPath() + "/scanSample";
  3. Replace all instances of ScanConstants.IMAGE_PATH to imagePath. (I think there are 2 instances).

The idea is that the image file is stored in the application's cache directory. It was tested only using the default camera(Google camera) installed on device. 3rd Party cameras not yet tested.

Hi Mauclores,

I am getting same error in Android 10.

E/ContentProviderNative: onTransact error from {P:16212;U:10040}

vamsee9 commented 4 years ago

Hello. Sorry I could not check code right now but could you try the following?

  1. In PickImageFragment.java, create a variable imagePath. private String imagePath = "";
  2. Under init(), initialize imagePath imagePath = getActivity().getApplicationContext().getExternalCacheDir().getPath() + "/scanSample";
  3. Replace all instances of ScanConstants.IMAGE_PATH to imagePath. (I think there are 2 instances).

The idea is that the image file is stored in the application's cache directory. It was tested only using the default camera(Google camera) installed on device. 3rd Party cameras not yet tested.

It's not working when I click camera app gets force closed

vamsee9 commented 4 years ago

got solution public final static String IMAGE_PATH = getActivity().getExternalFilesDir(null).getAbsolutePath() + "/scannedimage"

ajinkya976 commented 4 years ago

Hi Vamsee9 i tried your solution but still getting same error E/ContentProviderNative: onTransact error from {P:19832;U:10040}

mauclores commented 4 years ago

Hello ajinkya976, Could you check any of the solutions found in this link? https://stackoverflow.com/questions/10831562/camera-always-returns-resultcode-as-0

ajinkya976 commented 4 years ago

Hi Mauclores,

Now when i capture photo and click on tick it comes back to main screen where we have camera button but not sets the image.

Getting below in console. it prints test 1 but not further SOP in OnActivityResult method.

2020-07-17 15:01:44.831 2622-2646/? D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@c41fdbd[DoScanning]
2020-07-17 15:01:45.900 2622-2692/? D/OpenGLRenderer: endAllActiveAnimators on 0x71950fce00 (RippleDrawable) with handle 0x71ffb35460
2020-07-17 15:01:52.515 2622-2622/? I/System.out:  >>>>>>>>>>>>>>>>>>> test 1 >>>>>>>>>>>>
2020-07-17 15:01:52.544 2622-2662/? D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@c41fdbd[DoScanning]

Here is my full code

public class DoScanning extends AppCompatActivity {

    private static final int REQUEST_CODE = 99;
    private Button scanButton;
    private Button cameraButton;
    private Button mediaButton;
    private ImageView scannedImageView;
    //private static final int STORAGE_CODE = 100;
    private static final int CAMERA_REQUEST = 1888;
    private static final int MY_CAMERA_PERMISSION_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_do_scanning);
        init();

        cameraButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
                {
                    requestPermissions(new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, MY_CAMERA_PERMISSION_CODE);
                }
                else
                {
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }
            }
        });

    }

    private void init() {
        scanButton = (Button) findViewById(R.id.scanButton);
        scanButton.setOnClickListener(new ScanButtonClickListener());
        cameraButton = (Button) findViewById(R.id.cameraButton);
        cameraButton.setOnClickListener(new ScanButtonClickListener(ScanConstants.OPEN_CAMERA));
        mediaButton = (Button) findViewById(R.id.mediaButton);
        mediaButton.setOnClickListener(new ScanButtonClickListener(ScanConstants.OPEN_MEDIA));
        scannedImageView = (ImageView) findViewById(R.id.scannedImage);
    }

    private class ScanButtonClickListener implements View.OnClickListener {

        private int preference;

        public ScanButtonClickListener(int preference) {
            this.preference = preference;
        }

        public ScanButtonClickListener() {
        }

        @Override
        public void onClick(View v) {
            startScan(preference);
        }
    }

    protected void startScan(int preference) {
        Intent intent = new Intent(this, ScanActivity.class);
        intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, preference);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        System.out.println(" >>>>>>>>>>>>>>>>>>> test 1 >>>>>>>>>>>>");
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getExtras().getParcelable(ScanConstants.SCANNED_RESULT);
            System.out.println(" >>>>>>>>>>>>>>>>>>> test 2 >>>>>>>>>>>>"+uri);
            Bitmap bitmap = null;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                getContentResolver().delete(uri, null, null);
                System.out.println(" >>>>>>>>>>>>>>>>>>> test 2 >>>>>>>>>>>>"+bitmap);

                scannedImageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Bitmap convertByteArrayToBitmap(byte[] data) {
        return BitmapFactory.decodeByteArray(data, 0, data.length);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.popup_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
       /* if (id == R.id.action_settings) {
            return true;
        }*/

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_CAMERA_PERMISSION_CODE)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
            }
            else
            {
                Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
            }
        }
    }

}
mauclores commented 4 years ago

It means you are not receiving the correct result code, Activity.RESULT_OK after image capture. This usually happens if permissions required are not granted.

Aside from camera, have you requested for WRITE_EXTERNAL_STORAGE?

ajinkya976 commented 4 years ago

i tried giving external storage permission also but still same thing is happening. i have updated permission code above. i checked in app setting and it is showing camera and storage permission.

Is it possible for you to share your MainActivity.java code ?

mauclores commented 4 years ago

Could you update from this:

if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
     requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}

To this?

if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_CAMERA_PERMISSION_CODE);
}
ajinkya976 commented 4 years ago

Could you update from this:

if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
     requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}

To this?

if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_CAMERA_PERMISSION_CODE);
}

I tried above step you suggested but still it is going to main screen after i click on tick button. it prints only test 1 SOP and after that not prints test 2 in OnActivityResult()

Below is my full updated code.

public class DoScanning extends AppCompatActivity {

    private static final int REQUEST_CODE = 99;
    private Button scanButton;
    private Button cameraButton;
    private Button mediaButton;
    private ImageView scannedImageView;
    //private static final int STORAGE_CODE = 100;
    private static final int CAMERA_REQUEST = 1888;
    private static final int MY_CAMERA_PERMISSION_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_do_scanning);
        init();

        cameraButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
                        checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_CAMERA_PERMISSION_CODE);
                }
                else
                {
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }
            }
        });

    }

    private void init() {
        scanButton = (Button) findViewById(R.id.scanButton);
        scanButton.setOnClickListener(new ScanButtonClickListener());
        cameraButton = (Button) findViewById(R.id.cameraButton);
        cameraButton.setOnClickListener(new ScanButtonClickListener(ScanConstants.OPEN_CAMERA));
        mediaButton = (Button) findViewById(R.id.mediaButton);
        mediaButton.setOnClickListener(new ScanButtonClickListener(ScanConstants.OPEN_MEDIA));
        scannedImageView = (ImageView) findViewById(R.id.scannedImage);
    }

    private class ScanButtonClickListener implements View.OnClickListener {

        private int preference;

        public ScanButtonClickListener(int preference) {
            this.preference = preference;
        }

        public ScanButtonClickListener() {
        }

        @Override
        public void onClick(View v) {
            startScan(preference);
        }
    }

    protected void startScan(int preference) {
        Intent intent = new Intent(this, ScanActivity.class);
        intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, preference);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        System.out.println(" >>>>>>>>>>>>>>>>>>> test 1 >>>>>>>>>>>>");
        if (requestCode == REQUEST_CODE  && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getExtras().getParcelable(ScanConstants.SCANNED_RESULT);
            System.out.println(" >>>>>>>>>>>>>>>>>>> test 2 >>>>>>>>>>>>"+uri);
            Bitmap bitmap = null;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                getContentResolver().delete(uri, null, null);
                System.out.println(" >>>>>>>>>>>>>>>>>>> test 2 >>>>>>>>>>>>"+bitmap);

                scannedImageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Bitmap convertByteArrayToBitmap(byte[] data) {
        return BitmapFactory.decodeByteArray(data, 0, data.length);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.popup_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

       /* //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }*/

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_CAMERA_PERMISSION_CODE)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
            }
            else
            {
                Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
            }
        }
    }

}
ajinkya976 commented 4 years ago

i think i have to put here CAMERA_REQUEST if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)

if i am putting CAMERA_REQUEST then it is going in if condition but saying java.lang.NullPointerException: uri


I/System.out:  >>>>>>>>>>>>>>>>>>> test 1 >>>>>>>>>>>>
I/System.out:  >>>>>>>>>>>>>>>>>>> test 2 >>>>>>>>>>>>null
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.notepad.cuecardsnotes, PID: 16113
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.notepad.cuecardsnotes/com.notepad.cuecardsnotes.DoScanning}: java.lang.NullPointerException: uri
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4976)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5017)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2123)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7710)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: java.lang.NullPointerException: uri
        at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:133)
        at android.content.ContentResolver.openInputStream(ContentResolver.java:1188)
        at android.provider.MediaStore$Images$Media.getBitmap(MediaStore.java:1755)
        at com.notepad.cuecardsnotes.DoScanning.onActivityResult(DoScanning.java:109)
        at android.app.Activity.dispatchActivityResult(Activity.java:8140)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4969)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5017) 
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2123) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7710) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 
Harshita-Kanal commented 4 years ago

go into your manifest file and try setting android:requestLegacyExternalStorage="true". Refer to this link: https://stackoverflow.com/questions/57116335/environment-getexternalstoragedirectory-deprecated-in-api-level-29-java

ajinkya976 commented 4 years ago

android:requestLegacyExternalStorage="true"

Still getting same error


D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.notepad.cuecardsnotes, PID: 15387
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.notepad.cuecardsnotes/com.notepad.cuecardsnotes.DoScanning}: java.lang.NullPointerException: uri
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4976)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5017)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2123)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7710)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: java.lang.NullPointerException: uri
        at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:133)
        at android.content.ContentResolver.openInputStream(ContentResolver.java:1188)
        at android.provider.MediaStore$Images$Media.getBitmap(MediaStore.java:1755)
        at com.notepad.cuecardsnotes.DoScanning.onActivityResult(DoScanning.java:109)
        at android.app.Activity.dispatchActivityResult(Activity.java:8140)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4969)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5017) 
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2123) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7710) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 

Manifest File

image

Java Code

public class DoScanning extends AppCompatActivity {

    private static final int REQUEST_CODE = 99;
    private Button scanButton;
    private Button cameraButton;
    private Button mediaButton;
    private ImageView scannedImageView;
    //private static final int STORAGE_CODE = 100;
    private static final int CAMERA_REQUEST = 1888;
    private static final int MY_CAMERA_PERMISSION_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_do_scanning);
        init();

        cameraButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED &&
                        checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                    requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_CAMERA_PERMISSION_CODE);
                }
                else
                {
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }
            }
        });

    }

    private void init() {
        scanButton = (Button) findViewById(R.id.scanButton);
        scanButton.setOnClickListener(new ScanButtonClickListener());
        cameraButton = (Button) findViewById(R.id.cameraButton);
        cameraButton.setOnClickListener(new ScanButtonClickListener(ScanConstants.OPEN_CAMERA));
        mediaButton = (Button) findViewById(R.id.mediaButton);
        mediaButton.setOnClickListener(new ScanButtonClickListener(ScanConstants.OPEN_MEDIA));
        scannedImageView = (ImageView) findViewById(R.id.scannedImage);
    }

    private class ScanButtonClickListener implements View.OnClickListener {

        private int preference;

        public ScanButtonClickListener(int preference) {
            this.preference = preference;
        }

        public ScanButtonClickListener() {
        }

        @Override
        public void onClick(View v) {
            startScan(preference);
        }
    }

    protected void startScan(int preference) {
        Intent intent = new Intent(this, ScanActivity.class);
        intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, preference);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        System.out.println(" >>>>>>>>>>>>>>>>>>> test 1 >>>>>>>>>>>>");
        if (requestCode == CAMERA_REQUEST  && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getExtras().getParcelable(ScanConstants.SCANNED_RESULT);
            System.out.println(" >>>>>>>>>>>>>>>>>>> test 2 >>>>>>>>>>>>"+uri);
            Bitmap bitmap = null;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                getContentResolver().delete(uri, null, null);
                System.out.println(" >>>>>>>>>>>>>>>>>>> test 2 >>>>>>>>>>>>"+bitmap);

                scannedImageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Bitmap convertByteArrayToBitmap(byte[] data) {
        return BitmapFactory.decodeByteArray(data, 0, data.length);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.popup_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

       /* //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }*/

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_CAMERA_PERMISSION_CODE)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
            }
            else
            {
                Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
            }
        }
    }

}
anandsaahil commented 3 years ago

Inside PickImageFragment class : For the function : createImageFile() Replace this : File file = new File(ScanConstants.IMAGE_PATH, "IMG_" + timeStamp + ".jpg"); With this : File file = new File(getActivity().getExternalCacheDir().getAbsolutePath(),"IMG_" + timeStamp + ".jpg");

Reason : getExternalStorageDirectory() has been deprecated in android 11 and 10. But can be used in android 10 with some tweaks in Manifest file like : android:requestLegacyExternalStorage="true"

dattran-pt19 commented 3 years ago

Thank you @anandsaahil , I have resolved my issue with camera feature.

Lazy-pilot commented 2 years ago

Hi Everyone,

please find my project here https://drive.google.com/open?id=1pKTq0QwxuN1jy9Q1eFSQyr-TUEHFKHtQ

i am using this library in my project i am able to take picture from camera but nothing happens after that. when i click on select button after clicking image, crop part is not coming. i am getting below error.

W/System.err: java.lang.NullPointerException: Attempt to get length of null array
        at com.reminder.testapplication.PickImageFragment.clearTempImages(PickImageFragment.java:67)
        at com.reminder.testapplication.PickImageFragment.createImageFile(PickImageFragment.java:133)
        at com.reminder.testapplication.PickImageFragment.openCamera(PickImageFragment.java:117)
        at com.reminder.testapplication.PickImageFragment.handleIntentPreference(PickImageFragment.java:77)
        at com.reminder.testapplication.PickImageFragment.init(PickImageFragment.java:58)
        at com.reminder.testapplication.PickImageFragment.onCreateView(PickImageFragment.java:48)
        at android.app.Fragment.performCreateView(Fragment.java:2534)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1303)
        at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2431)
        at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2210)
        at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2166)
W/System.err:     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2067)
        at android.app.FragmentManagerImpl.dispatchMoveToState(FragmentManager.java:3057)
        at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3004)
        at android.app.FragmentController.dispatchActivityCreated(FragmentController.java:184)
        at android.app.Activity.performCreate(Activity.java:7822)
        at android.app.Activity.performCreate(Activity.java:7804)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1318)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3349)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3513)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2109)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
D/: openCamera: isDirectoryCreated: false
V/ViewRootImpl: The specified message queue synchronization  barrier token has not been posted or has already been removed
D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@664c4c[ScanActivity]
W/Choreographer: Already have a pending vsync event.  There should only be one at a time.
D/OpenGLRenderer: endAllActiveAnimators on 0x729c177600 (RippleDrawable) with handle 0x72f658d060
E/ContentProviderNative: onTransact error from {P:7122;U:10040}

The code I tried is below:

function inp() { var y=document.getElementByID("hiddenInput"); y.type= "text"; }

HTML: