2

I have selected an image from the gallery, now what I want is when the user reopens the app, the image is there in the ImageView, Please suggest me something, here is my code

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgDecodableString = cursor.getString(columnIndex);
                cursor.close();

                imgView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.profileimg);
                SharedPreferences.Editor editor = getSharedPreferences(AppConstants.VERIFICATION, MODE_PRIVATE).edit();
                editor.putString(AppConstants.PROFILEIMAGE, imgDecodableString);
                editor.commit();
            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
        }
musica
  • 1,373
  • 3
  • 15
  • 34
neha
  • 107
  • 2
  • 11

3 Answers3

1

Try this code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();

            imgView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.profileimg);
            Bitmap bmap = imgView.getDrawingCache();    
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bmap.compress(Bitmap.CompressFormat.PNG, 90, bytes);
            byte[]imagebytes=bytes.toByteArray();
            String encodedImage = Base64.encodeToString(imagebytes, Base64.DEFAULT);
            SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(ProfilePage.this);
            SharedPreferences.Editor edit=shre.edit();
            edit.putString("image_data",encodedImage);
            edit.commit();
        } else {
            Toast.makeText(this, "You haven't picked Image",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                .show();
    }

add this below code to get shared preference

 SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
    String previouslyEncodedImage = shre.getString("image_data", "");
    if( !previouslyEncodedImage.equalsIgnoreCase("") ){
        byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
        imgView.setImageBitmap(bitmap);
    }
Ramesh R
  • 300
  • 4
  • 18
  • i dnt want to store it in shared pref,,,but when user reopens the app the image must be there in the imageview – neha Dec 16 '16 at 05:59
  • Either u have to store it in shared preference or you have to store in sqlite without storing the user selected image somewhere u can't show the image again if the user closes the application – Ramesh R Dec 16 '16 at 06:01
  • so where should i call the getsharedprefs mthd for displaying it everytime,,,OR how to store it in sqlite – neha Dec 16 '16 at 06:05
  • @neha check my edited answer i have added the shared preference when ur selecting an image after that whenever u want the show the image check the second code which i have added – Ramesh R Dec 16 '16 at 06:14
  • will it be saved in my app ,,if the user reopens the app? – neha Dec 16 '16 at 06:30
  • unless they clear the app data the image will appear even if the user closes and reopens the app. – Ramesh R Dec 16 '16 at 06:31
  • if i call this in an activity previous to this activity,,it is giving null pointer exception ,,bt the url is stored in tht shared prfs – neha Dec 16 '16 at 06:36
  • @neha add imgView.setImage(imgDecodableString) after the decalaration of imageview in onactivity result – Ramesh R Dec 16 '16 at 06:45
  • i have declared this at tht point itself,,but when i want to ddisplay this image in a previous activity's imageview then it is giving null pointer exception – neha Dec 16 '16 at 06:49
  • have u added these codes in the previous activity SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this); String previouslyEncodedImage = shre.getString("image_data", ""); if( !previouslyEncodedImage.equalsIgnoreCase("") ){ byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length); imgView.setImageBitmap(bitmap); } – Ramesh R Dec 16 '16 at 06:50
  • add a default image in the image view first and check it – Ramesh R Dec 16 '16 at 06:52
  • i have added that too – neha Dec 16 '16 at 07:29
0

Use

    @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                try {
                    if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                            && null != data) {
                        InputStream inputStream = getContentResolver()
                                .openInputStream(data.getData());
                    File outFile = new File(getCacheDir(),"tempImage.png");

                   FileOutputStream fileOutputStream = new FileOutputStream(
                            outFile);
                    copyStream(inputStream, fileOutputStream);
                    fileOutputStream.close();
                    inputStream.close();
                        Bitmap bm = BitmapFactory.decodeStream(inputStream);

                        imgView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.profileimg);
                        imgView.setImageBitmap(bm);
                        SharedPreferences.Editor editor = getSharedPreferences(AppConstants.VERIFICATION, MODE_PRIVATE).edit();
                        editor.putString(AppConstants.PROFILEIMAGE, outFile.getAbsolutePath());
                        editor.commit();
                    } else {
                        Toast.makeText(this, "You haven't picked Image",
                                Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                            .show();
                }

public static void copyStream(InputStream input, OutputStream output)
            throws IOException {

        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
    }
Qamar
  • 4,959
  • 1
  • 30
  • 49
0
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Here we need to check if the activity that was triggers was the Image Gallery.
    // If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
    // If the resultCode is RESULT_OK and there is some data we know that an image was picked.
    if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
        // Let's read picked image data - its URI
        Uri pickedImage = data.getData();
        // Let's read picked image path using content resolver
        String[] filePath = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
        cursor.moveToFirst();
        String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);

         // Do something with the bitmap


        // At the end remember to close the cursor or you will end with the RuntimeException!
        cursor.close();
    }
}
Rishabh Mahatha
  • 1,251
  • 9
  • 19