0

i'm doing an app to save an image from gallery into a ImageView, and for that i have to save in sharedPreference for when i leave application and return, the image is still there.

ps: I already read one question here with same title, but doesnt worked for me

Someone could help me? Please

part of JAVA file

++++++++++++++++++++++++

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("data",  context.MODE_PRIVATE);


imgButton = (ImageView) findViewById(R.id.AddPic);
imgButton.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) {
        Intent GaleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(GaleryIntent, RESULT_LOAD_IMAGE);
    } 
}); 


} 
@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
    SelectedImage = data.getData();



  performCrop();


} 

else if(requestCode == PIC_CROP){

    Bundle extras = data.getExtras();
    //get the cropped bitmap
    Bitmap thePic = extras.getParcelable("data");


    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    thePic.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap    object   
    byte[] byteArray = baos.toByteArray();

    String imageString= Base64.encodeToString(byteArray , Base64.DEFAULT);

    byte[] imageBytes = Base64.decode(imageString.getBytes());
    imgButton.setImageBitmap(BitmapFactory.decodeByteArray(imageBytes, 0,    imageBytes.length));



}
}
private void performCrop() {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP"); 
        cropIntent.setDataAndType(SelectedImage, "image/*");
        cropIntent.putExtra("crop", "true");
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("outputX", 256);
        cropIntent.putExtra("outputY", 256);
        cropIntent.putExtra("return-data", true);
        startActivityForResult(cropIntent, PIC_CROP);
    }
    catch(ActivityNotFoundException anfe){
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }       
}}

+++++++++++++++++++++++++

i tried this, the first answer : How to save cropped image uri in shared Preference but didnt work

maybe i have to convert bitmap to string or do something else, but i dont know

Thakns anyway

Community
  • 1
  • 1

2 Answers2

0

You can save cropped image bitmap in SharedPreference.. As we can only store Boolean, Float, Int, Long, String values in SharedPreference. But one thing you can do is converting Bitmap to Base64 String and save in SharedPreference and then retrieve string when ever user open app..

convert bitmap to byte array like this :

ByteArrayOutputStream baos = new ByteArrayOutputStream();  
thePic.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object   
byte[] byteArray = baos.toByteArray();

get String from byte array like this

String imageString= Base64.encodeToString(byteArray , Base64.DEFAULT);

now save this String in SharedPreference and when you want to show image just get this String from SharedPreference and show in ImageView like this

byte[] imageBytes = Base64.decode(imageString.getBytes());
imageView.setImageBitmap(BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length));
Mustanser Iqbal
  • 5,017
  • 4
  • 18
  • 36
0
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;


public class FetchPath {
    /**
     * Get a file path from a Uri. This will get the the path for Storage Access
     * Framework Documents, as well as the _data field for the MediaStore and
     * other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri     The Uri to query.
     * @author paulburke
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

}

Usage

Uri photoUri = data.getData();
 if (photoUri != null) {
 String filePath = FetchPath.getPath(this, photoUri);
  }
Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73