0

My app was working fine before i updated the software version of my galaxy tab 2, but after the update to version7.0, the camera function is not working right. it takes a picture, shows the preview, but crashes after i press "ok" on the preview page. when i check the gallery, the image is also not saved. This are my codes.

public void btnCameraOnClick(View v)
{
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent,CAMERA_REQUEST);
}

in the manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

not sure if there is anything wrong this is the log, not sure if its whats needed either

09-18 11:46:01.520 8795-8795/henderson.application E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: henderson.application, PID: 8795
                                                                 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data flg=0x1 launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 } (has extras) }} to activity {henderson.application/henderson.application.Application_admin_1}: java.lang.NullPointerException: uri
                                                                     at android.app.ActivityThread.deliverResults(ActivityThread.java:4524)
                                                                     at android.app.ActivityThread.handleSendResult(ActivityThread.java:4567)
                                                                     at android.app.ActivityThread.-wrap22(ActivityThread.java)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1695)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:154)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:6780)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
                                                                  Caused by: java.lang.NullPointerException: uri
                                                                     at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:111)
                                                                     at android.content.ContentResolver.query(ContentResolver.java:519)
                                                                     at android.content.ContentResolver.query(ContentResolver.java:478)
                                                                     at henderson.application.Application_admin_1.onActivityResult(Application_admin_1.java:114)
                                                                     at android.app.Activity.dispatchActivityResult(Activity.java:7273)
                                                                     at android.app.ActivityThread.deliverResults(ActivityThread.java:4520)
                                                                     at android.app.ActivityThread.handleSendResult(ActivityThread.java:4567) 
                                                                     at android.app.ActivityThread.-wrap22(ActivityThread.java) 
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1695) 
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                     at android.os.Looper.loop(Looper.java:154) 
                                                                     at android.app.ActivityThread.main(ActivityThread.java:6780) 
                                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496) 
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386) 

codes for activity

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


    switch (requestCode) {
        case SELECTED_PICTURE:
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                String[] projection = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(uri, projection, null, null, null); // line 114
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(projection[0]);
                image_file_path = cursor.getString(columnIndex);
                cursor.close();

                File f = new File(image_file_path);

log error for Sagar

09-18 13:59:29.393 16404-16404/henderson.application E/AndroidRuntime: FATAL EXCEPTION: main
                                                                   Process: henderson.application, PID: 16404
                                                                   android.os.FileUriExposedException: file:///storage/emulated/0/tmp exposed beyond app through ClipData.Item.getUri()
                                                                       at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
                                                                       at android.net.Uri.checkFileUriExposed(Uri.java:2346)
                                                                       at android.content.ClipData.prepareToLeaveProcess(ClipData.java:832)
                                                                       at android.content.Intent.prepareToLeaveProcess(Intent.java:9514)
                                                                       at android.content.Intent.prepareToLeaveProcess(Intent.java:9499)
                                                                       at android.app.Instrumentation.execStartActivity(Instrumentation.java:1525)
                                                                       at android.app.Activity.startActivityForResult(Activity.java:4403)
                                                                       at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
                                                                       at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
                                                                       at android.app.Activity.startActivityForResult(Activity.java:4362)
                                                                       at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:871)
                                                                       at henderson.application.Application_admin_1$1.onClick(Application_admin_1.java:228)
                                                                       at android.view.View.performClick(View.java:6257)
                                                                       at android.widget.TextView.performClick(TextView.java:11149)
                                                                       at android.view.View$PerformClick.run(View.java:23705)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6780)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

error is at startActivityForResult(intent, CAMERA_REQUEST);

Wei Xiong
  • 167
  • 4
  • 13
  • post the log please – John Joe Sep 18 '17 at 02:31
  • You should check permission in your code . Because above Android 6.0,you need to check it in your code . – KeLiuyue Sep 18 '17 at 02:33
  • You can use [this library](https://github.com/permissions-dispatcher/PermissionsDispatcher) in your code . – KeLiuyue Sep 18 '17 at 02:35
  • Did you try to catch the error? I believe it might be related to runtime permissions. Please post the log here after catching the error. – Aman Sep 18 '17 at 03:15
  • how do i print out the log into a text file? @Aman – Wei Xiong Sep 18 '17 at 03:32
  • i also think its the runtime permissions but i already set all permissions to acept in the app manager – Wei Xiong Sep 18 '17 at 03:33
  • Why do you need the log in a text file? Just put the function, where this activity is happening and you think is the source of crash in a try block. And below the try block, write a catch block. Something like try{ //Possible error area in the code } catch(Exception e){ Log.e("LOG_ERROR", e.getMessage) }; – Aman Sep 18 '17 at 03:40
  • hm... just ran the code in debug, does not go into the catch. gets stuck in looper class – Wei Xiong Sep 18 '17 at 03:44
  • As a side note, since you are calling an external application to take the picture for you, you don't need the CAMERA permission. The crash appears to be caused by Hangout. I recommend that you make sure you have the latest version – njzk2 Sep 18 '17 at 04:00
  • think i found the right error, just edited the qn – Wei Xiong Sep 18 '17 at 04:06
  • Possible duplicate of [android camera : Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity](https://stackoverflow.com/questions/19042511/android-camera-failure-delivering-result-resultinfowho-null-request-0-resul) – Amit Vaghela Sep 18 '17 at 04:18
  • this is not a null pointer exception – Wei Xiong Sep 18 '17 at 04:40
  • Finally got the camera to work, it does save in the gallery but when i try to view it in the gallery, it just shows an exclaimation mark – Wei Xiong Sep 18 '17 at 09:33

2 Answers2

0

becouse above version 6.0 needs runtime permission

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.yalantis.ucrop.UCrop;

import java.io.File;

public class MainActivity extends AppCompatActivity {
LinearLayout linsketch,lincamera,linalpha,linsigno;
    public static File mFileTemp;
    Uri selectedImageUri;
    public static final int RESULT_FROM_CAMERA = 1;
    public static final int RESULT_FROM_GALLERY = 2;
    String pathname;
    public static final int RequestPermissionCode = 104;
    private static final String SAMPLE_CROPPED_IMAGE_NAME = "SampleCropImage";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();

    }

    private void init() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mFileTemp = new File(Environment.getExternalStorageDirectory(),
                    Utils.TEMP_FILE_NAME);
            pathname=mFileTemp+"";
            Toast.makeText(getApplicationContext(),pathname,Toast.LENGTH_SHORT).show();
        } else {
            mFileTemp = new File(getFilesDir(), Utils.TEMP_FILE_NAME);
            pathname=mFileTemp+"";
        }
        EnableRuntimePermission();

        linsketch=(LinearLayout)findViewById(R.id.linsketch);
        lincamera=(LinearLayout)findViewById(R.id.lincamera);
        linalpha=(LinearLayout)findViewById(R.id.linalpha);
        linsigno=(LinearLayout)findViewById(R.id.linsigno);
       linsketch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Dialog dialog = new Dialog(MainActivity.this);

                dialog.requestWindowFeature(1);
                dialog.setContentView(R.layout.gallary_or_camera);
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));

                ImageView gal = (ImageView) dialog.findViewById(R.id.gall);
                ImageView cam=(ImageView)dialog.findViewById(R.id.cam);
                gal.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                       // Toast.makeText(getApplicationContext(),"you clicked at gallery",Toast.LENGTH_SHORT).show();
                        pickFromGallery();
                    }
                });
                cam.setOnClickListener(new View.OnClickListener() {
                                           @Override
                                           public void onClick(View v) {
                                               dialog.dismiss();
                                               try {
                                                   Thread.sleep(500);
                                               } catch (InterruptedException e) {
                                                   // TODO Auto-generated catch block
                                                   e.printStackTrace();
                                               }
                                               Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

                                               intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFileTemp));
                                               startActivityForResult(intent, RESULT_FROM_CAMERA);

                                           }
                                       }
                );

dialog.show();
            }
        });
    }


    private void EnableRuntimePermission() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                + ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale
                    (MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) ||
                    ActivityCompat.shouldShowRequestPermissionRationale
                            (MainActivity.this, android.Manifest.permission.CAMERA)) {

                Toast.makeText(MainActivity.this, "Allow permissions to Edit the Image", Toast.LENGTH_LONG).show();
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(
                            new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, RequestPermissionCode);
                }
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {

            case RequestPermissionCode:

                if (grantResults.length > 0) {
                    boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                    boolean writeExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;

                    if (cameraPermission && writeExternalFile) {
                    } else {
                        Toast.makeText(MainActivity.this, "Allow permissions to Edit the Image", Toast.LENGTH_LONG).show();
                    }
                    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFileTemp));
                    startActivityForResult(intent, RESULT_FROM_CAMERA);
                }
                break;
        }
    }
    private void pickFromGallery() {

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(Intent.createChooser(intent, getString(R.string.label_select_picture)), RESULT_FROM_GALLERY);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == RESULT_FROM_GALLERY) {
                final Uri selectedUri = data.getData();
                Log.d("sss",""+selectedUri);
                if (selectedUri != null) {
                    startCropActivity(data.getData());
                } else {
                    Toast.makeText(MainActivity.this, R.string.toast_cannot_retrieve_selected_image, Toast.LENGTH_SHORT).show();
                }
            }
            else  if(requestCode==RESULT_FROM_CAMERA){

                File imageFile = new File(pathname);

              Uri  picUri = Uri.fromFile(imageFile);
                startCropActivity(picUri);

            }else if (requestCode == UCrop.REQUEST_CROP) {
                handleCropResult(data);
            }
        }
    }
    private void startCropActivity(@NonNull Uri uri) {
        String destinationFileName = SAMPLE_CROPPED_IMAGE_NAME;

        destinationFileName += ".png";
        UCrop uCrop = UCrop.of(uri, Uri.fromFile(new File(getCacheDir(), destinationFileName)));


        uCrop.start(MainActivity.this);
    }
    private void handleCropResult(@NonNull Intent result) {
        final Uri resultUri = UCrop.getOutput(result);
        if (resultUri != null) {
            ResultActivity.startWithUri(MainActivity.this, resultUri);
        } else {
            Toast.makeText(MainActivity.this, R.string.toast_cannot_retrieve_cropped_image, Toast.LENGTH_SHORT).show();
        }
    }
}
Sagar Patel
  • 224
  • 1
  • 9
0

put this on your camera click code

camera.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if(Build.VERSION.SDK_INT>=24){
                        try{
                            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
                            m.invoke(null);
                        }catch(Exception e){
                            e.printStackTrace();
                        }
                    }

                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFileTemp));
                    startActivityForResult(intent, RESULT_FROM_CAMERA);

                } catch (ActivityNotFoundException e) {
                    // Log.d(TAG, "cannot take picture", e);
                }

            }
        });
Sagar Patel
  • 224
  • 1
  • 9