1

This is my code got from here

    public class CatFragment extends Fragment implements OnClickListener{

        private DBCreater dbCreate;

        private static final int SELECT_PICTURE = 1;

        private String selectedImagePath = "android.resource://com.example.abcd/" + R.drawable.pets;
        private ImageView img;
        //private Button imgBtn;

        private Uri mCropImagedUri;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View gv = inflater.inflate(R.layout.new_pet, null);

            Spinner sp = (Spinner) gv.findViewById(R.id.ETPetType); 
            // get reference 
            sp.setAdapter(new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_spinner_dropdown_item, petType));

            Button btnSubmit = (Button) gv.findViewById(R.id.ButtonNext);
            btnSubmit.setOnClickListener(this);

            img = (ImageView)gv.findViewById(R.id.ImageView01);
        ((Button) gv.findViewById(R.id.ETPetImg))
                        .setOnClickListener(new OnClickListener() {
                            public void onClick(View arg0) {
                                try {
                                    Intent intent = new Intent();
                                    intent.setType("image/*");
                                    intent.setAction(Intent.ACTION_GET_CONTENT);
                                    intent.putExtra("crop", "true");
                                    intent.putExtra("aspectX", 0);
                                    intent.putExtra("aspectY", 0);
                                    intent.putExtra("outputX", 200);
                                    intent.putExtra("outputY", 200);
                                    intent.putExtra("return-data", false);

                                    File f = createNewFile("CROP_");
                                    try {
                                        f.createNewFile();
                                    } catch (IOException ex) {
                                        Log.e("io", ex.getMessage());
                                    }

                                    mCropImagedUri = Uri.fromFile(f);
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                            mCropImagedUri);
                                    // start the activity - we handle returning in
                                    // onActivityResult
                                    startActivityForResult(intent, SELECT_PICTURE);
                                                            } catch (ActivityNotFoundException anfe) {
                                    // display an error message

                                }
                            }
                        });

                return gv;

            }


            private File createNewFile(String prefix){
                if(prefix==null || "".equalsIgnoreCase(prefix)){
                    prefix="IMG_";
                }
                File newDirectory = new File(Environment.getExternalStorageDirectory()+"/Android/data/com.example.abcd/files/");
                if(!newDirectory.exists()){
                    if(newDirectory.mkdir()){
                        Log.d(this.getClass().getName(), newDirectory.getAbsolutePath()+" directory created");
                    }
                }
                File file = new File(newDirectory,(prefix+System.currentTimeMillis()+".jpg"));
                if(file.exists()){
                    //this wont be executed
                    file.delete();
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                return file;
            }


            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (resultCode == Activity.RESULT_OK) {
                    if (requestCode == SELECT_PICTURE) {
                        Uri selectedImageUri = data.getData();
                        selectedImagePath = getPath(selectedImageUri); //To get image path
                        System.out.println("Image Path : " + selectedImagePath);
                        img.setImageURI(selectedImageUri);


                    }
                }
            }

public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        //Cursor cursor = managedQuery(uri, projection, null, null, null);
        Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //access the database
        dbCreate = new DBCreater(getActivity());

    }



    @Override
    public void onClick(View v) {
        displayNextAlert();

    }

By using this code I'm able to crop the image but It's not saving and returns a Toast message stats Unable to Save the cropped image. I couldn't see any other errors in LogCat. Please someone help? Thanks in advance.

LogCat:

11-15 07:15:38.215: E/AndroidRuntime(27214): FATAL EXCEPTION: main
11-15 07:15:38.215: E/AndroidRuntime(27214): java.lang.RuntimeException: Unable to resume activity {com.example.abcd/com.example.abcd.MainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.abcd/com.example.abcd.MainActivity}: java.lang.NullPointerException
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2919)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2948)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2354)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.app.ActivityThread.access$700(ActivityThread.java:159)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.os.Looper.loop(Looper.java:176)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.app.ActivityThread.main(ActivityThread.java:5419)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at java.lang.reflect.Method.invokeNative(Native Method)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at java.lang.reflect.Method.invoke(Method.java:525)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at dalvik.system.NativeStart.main(Native Method)
11-15 07:15:38.215: E/AndroidRuntime(27214): Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.abcd/com.example.abcd.MainActivity}: java.lang.NullPointerException
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3500)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2906)
11-15 07:15:38.215: E/AndroidRuntime(27214):    ... 12 more
11-15 07:15:38.215: E/AndroidRuntime(27214): Caused by: java.lang.NullPointerException
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1147)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.content.ContentResolver.query(ContentResolver.java:401)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.content.ContentResolver.query(ContentResolver.java:360)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at com.example.abcd.NewPetsFragment.getPath(NewPetsFragment.java:155)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at com.example.abcd.NewPetsFragment.onActivityResult(NewPetsFragment.java:143)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.app.Activity.dispatchActivityResult(Activity.java:5567)
11-15 07:15:38.215: E/AndroidRuntime(27214):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3496)
11-15 07:15:38.215: E/AndroidRuntime(27214):    ... 13 more
Community
  • 1
  • 1
vinoth kumar
  • 47
  • 2
  • 8
  • Check out solution on this post [link](http://stackoverflow.com/questions/11737659/how-to-crop-camera-images-for-portrait-view-in-android-version-3-0) – Wildroid Nov 13 '14 at 18:37
  • No it's not working and I don't think it's the solution – vinoth kumar Nov 13 '14 at 18:42
  • Could your Android's media not be mounted (e.g. older device plugged into the computer) where it can't write to the external storage? Do you have the permissions for WRITE_EXTERNAL_STORAGE? – Cruceo Nov 13 '14 at 20:37
  • @vinothkumar see my answer below. I got the code to work. Tested on Android 4.4.4 device not emulator. – Wildroid Nov 13 '14 at 21:31

1 Answers1

1

I got the code to work by changing the saved directory path as follows:

 File newDirectory = new File(Environment.getExternalStorageDirectory()+"/test/");

Reason: I could not save to write-protected directory "/Android/data/com.example.abcd/files/"

and by following changes to onActivityResult:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
        //    Uri selectedImageUri = data.getData();
        //    selectedImagePath = getPath(selectedImageUri); //To get image path

            selectedImagePath = mCropImagedUri.getPath(); //To get image path

            System.out.println("Image Path : " + selectedImagePath);
         //   img.setImageURI(selectedImageUri);


        }
    }
} 

NOTE: You probably don't need to comment out the img.setImageURI line. I had to for test purpose.

Make sure you have added the write permission in AndroidManifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Wildroid
  • 864
  • 7
  • 9
  • Thx. Hope this one will work. I'll mark it as correct answer once I test it. – vinoth kumar Nov 14 '14 at 07:20
  • @ Wildroid : it's solved my question. But I want to ask you that is there is anyway to store in "/Android/data/com.example.abcd/files/" ? Also my app is crashing after cropping and saving the image. Could you please solve this issue? I think that I need to get the new path for the cropped image. How can I do it? – vinoth kumar Nov 14 '14 at 11:05
  • @vinothkumar Are you testing on device or emulator? Note: If you save to sdcard/Android/data/full.package.name, the cropped images get deleted on app uninstall. As far as I know, you need root access to save into Android data directory. – Wildroid Nov 14 '14 at 13:20
  • thx. but the code that u given is crashing after saving the cropped image. I think onActivityResult need to be modified. I don't know how. Could you please solve it for me? – vinoth kumar Nov 14 '14 at 15:08
  • @vinothkumar It works fine with me. No crash. Can you check the logcat error. See why it crashes. Maybe it is another issue causing crash. You can try to post the logcat error so I can try to solve issue. Maybe it is setImageURI causing error. It has to be the code after saving image. Check the directory. Is the image saved? – Wildroid Nov 14 '14 at 18:05
  • @ Wildroid : Please see my edited question for LogCat and I added more code from the Fragment file. (It crashing only after saving the cropped image) As you said I think setImageURI causing the error, but I couldn't figure out how to fix it. Thanks. – vinoth kumar Nov 15 '14 at 07:20
  • @vinothkumar you need to set bitmap to img view. After setImageURI - try adding: Bundle extras = data.getExtras(); Bitmap thePic = extras.getParcelable("data"); before setting img. Then replace as follows: img.setImageBitmap(thePic); – Wildroid Nov 15 '14 at 16:42
  • Still the same result. Please check [this] (http://stackoverflow.com/questions/26945429/unable-to-resume-activity-after-saving-cropped-image-android) .I'm using Fragment. Plz solve if possible. thx – vinoth kumar Nov 15 '14 at 17:58
  • 1
    @vinothkumar In OnActivityResult(): if(data!=null) { Bitmap thePic = (Bitmap) data.getExtras().get("data"); img.setImageBitmap(thePic); } – Wildroid Nov 15 '14 at 22:27
  • thx Wildroid, It's works fine now. but the image is not visible on the form preview. I can only see the image after submitting the form on SQLite. Why is that? it should be visible as I setting it on img (imageview) – vinoth kumar Nov 17 '14 at 16:58
  • @vinothkumar sometimes or some devices, data may return null after cropping in OnActivityResult. A workaround would be to set the image preview from the saved location (after cropped image is saved) rather than from data.getExtras - So, you can add an else function to do that (meaning if data is null). – Wildroid Nov 18 '14 at 01:39
  • @vinothkumar I will post answer in your other post since it is a different question. – Wildroid Nov 18 '14 at 12:30