0

I want to load the image in ImageView after cropping the image and save it. But when it's resumes it gets crashed, but image is saving on selected location. I think the problem is in selectedImageUri. But I couldn't figure it out how to solve. Please someone help. Thanks in advance.

Code:

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()+"/test1/");
                    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();

        }

LogCat:

7214): 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

Edited:

I changed OnActivityResult() like this:

if(data!=null) { 
                     Bitmap thePic = (Bitmap) data.getExtras().get("data");
                     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
                     String filename = preferences.getString("file_name", ""); // value to retrieve
                     String path = Environment.getExternalStorageDirectory()+"/PetSitter/Pet Images/" + filename;
                     img.setImageURI(Uri.parse(path.toString()));
                     } else {
                     // In createNewFile, make sure you already saved the filename (prefix+System.currentTimeMillis()+".jpg"), for example, to sharedpreferences then get the filename and apply in path 
                     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
                     String filename = preferences.getString("file_name", ""); // value to retrieve
                     String path = Environment.getExternalStorageDirectory()+"/PetSitter/Pet Images/" + filename;
                     BitmapFactory.Options bfo = new BitmapFactory.Options();
                     bfo.inSampleSize = 1;
                     Bitmap bmp = BitmapFactory.decodeFile(path, bfo);
                     img.setImageBitmap(bmp);
                    }

It's seems to be working with image preview and everything. But what do thing? Is it a good practice to do? and how will be the memory usage by using like this?

vinoth kumar
  • 47
  • 2
  • 8

4 Answers4

1

In OnActivityResult():

             if(data!=null) { 
             Bitmap thePic = (Bitmap) data.getExtras().get("data");
             img.setImageBitmap(thePic);
             } else {
             // In createNewFile, make sure you already saved the filename (prefix+System.currentTimeMillis()+".jpg"), for example, to sharedpreferences then get the filename and apply in path 
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
String filename = preferences.getString("file_name", ""); // value to retrieve
             String path = Environment.getExternalStorageDirectory()+"/test1/" + filename;
             BitmapFactory.Options bfo = new BitmapFactory.Options();
             bfo.inSampleSize = 1;
             Bitmap bmp = BitmapFactory.decodeFile(path, bfo);
             img.setImageBitmap(bmp);
            }

In createNewFile

                private File createNewFile(String prefix){
                        if(prefix==null || "".equalsIgnoreCase(prefix)){
                            prefix="IMG_";
                        }
                        File newDirectory = new File(Environment.getExternalStorageDirectory()+"/test1/");
                        if(!newDirectory.exists()){
                            if(newDirectory.mkdir()){
                                Log.d(this.getClass().getName(), newDirectory.getAbsolutePath()+" directory created");
                            }
                        }
    // modifications applied here
    long mDate = System.currentTimeMillis();
                        File file = new File(newDirectory,(prefix+mDate+".jpg"));
String filename = prefix+mDate+".jpg";
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("file_name", filename); // value to store
editor.commit();
                        if(file.exists()){
                            //this wont be executed
                            file.delete();
                            try {
                                file.createNewFile();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                        return file;
                    }
Wildroid
  • 864
  • 7
  • 9
  • 'File file = new File(newDirectory,(prefix+System.currentTimeMillis()+".jpg"));' in 'createNewFile(String prefix)' how could I call here? – vinoth kumar Nov 18 '14 at 14:51
  • I used 'selectedImagePath = mCropImagedUri.getPath(); //To get image path' to get the file name. But It's not showing in ImageView. The way I used is right? – vinoth kumar Nov 18 '14 at 14:59
  • No - you need to get filename using sharedpreferences or temp database where you save the filename since you are using system.currenttimemillis in the name of the file. Do you know how to save filename to sharedpreferences? – Wildroid Nov 18 '14 at 15:05
  • Nope how could I implement it? – vinoth kumar Nov 18 '14 at 15:11
  • See edited answer above - how to use sharedpreferences – Wildroid Nov 18 '14 at 15:29
  • thx. It's works fine but still not showing the preview (ImageView).:( – vinoth kumar Nov 18 '14 at 15:38
  • I think that I need to refresh the fragment. What do you think about it? – vinoth kumar Nov 18 '14 at 15:55
  • Are you previewing cropped image after you save or before you save? I would show preview after saving. Somehow the img view is not getting the updated image. – Wildroid Nov 18 '14 at 15:58
  • I want to preview it after saving cropped image. At the moment It's saving the cropped image but not preview it. And after the form submission I'm able to view it in list. – vinoth kumar Nov 18 '14 at 16:01
0
Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));

And

    private String getRealPathFromURI(Uri contentURI) {
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        return contentURI.getPath();
    } else { 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
        return cursor.getString(idx); 
    }
}
Jibran Khan
  • 3,236
  • 4
  • 37
  • 50
Rathan Kumar
  • 2,567
  • 2
  • 17
  • 24
  • getting error on 'getContentResolver()' and how do I set 'File' into 'ImageView' (I mean imageFile)? – vinoth kumar Nov 15 '14 at 12:42
  • now I'm getting this error: '11-15 13:48:46.351: E/AndroidRuntime(19350): 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' – vinoth kumar Nov 15 '14 at 13:45
0

Try this in onActivityResult

Bitmap photo = (Bitmap) data.getExtras().get("data"); 
                img.setImageBitmap(photo);
Jibran Khan
  • 3,236
  • 4
  • 37
  • 50
  • Thx. But now I'm getting this error: '11-15 13:48:46.351: E/AndroidRuntime(19350): 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' – vinoth kumar Nov 15 '14 at 13:45
  • You are using Fragments therefore the activity is in state loss. Please refer to this http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html and http://stackoverflow.com/questions/16265733/failure-delivering-result-onactivityforresult – Jibran Khan Nov 15 '14 at 13:57
  • Thx for the links but how could I implement it? – vinoth kumar Nov 15 '14 at 15:08
  • Ok add super.onActivityResult(requestCode,resultCode, data); as the first line of onActivityResult – Jibran Khan Nov 15 '14 at 15:54
0

I changed OnActivityResult() like this:

if(data!=null) { 
                     Bitmap thePic = (Bitmap) data.getExtras().get("data");
                     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
                     String filename = preferences.getString("file_name", ""); // value to retrieve
                     String path = Environment.getExternalStorageDirectory()+"/PetSitter/Pet Images/" + filename;
                     img.setImageURI(Uri.parse(path.toString()));
                     } else {
                     // In createNewFile, make sure you already saved the filename (prefix+System.currentTimeMillis()+".jpg"), for example, to sharedpreferences then get the filename and apply in path 
                     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
                     String filename = preferences.getString("file_name", ""); // value to retrieve
                     String path = Environment.getExternalStorageDirectory()+"/PetSitter/Pet Images/" + filename;
                     BitmapFactory.Options bfo = new BitmapFactory.Options();
                     bfo.inSampleSize = 1;
                     Bitmap bmp = BitmapFactory.decodeFile(path, bfo);
                     img.setImageBitmap(bmp);
                    }

It's seems to be working with image preview and everything.

vinoth kumar
  • 47
  • 2
  • 8