简体   繁体   中英

Save image is SharedPreferences after Image is get from camera or upload from gallery and display at ImageView (Android Studio)

I have a problem as mention at the question above. All data from EditText, RadioButton and Spinner can be saved at SharedPreference and display back at another activity. But i dont know how to save the Image after I get it from camera or upload from gallery and display at ImageView. Any method? Please help me.

//Code for saving in SharedPreferences

    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences sharedPref = getSharedPreferences("MyData",MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("title",etTitle.getText().toString());
            editor.putString("year",etYear.getText().toString());
            editor.putString("month",etMonth.getText().toString());

            // get selected radio button from radioGroup
            int selectedId = rgSuggestWill.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            radioButton = findViewById(selectedId);
            editor.putString("suggestionwill",radioButton.getText().toString());
            if (spReviewer.getSelectedItem().toString().equals("Please choose")){

                AlertDialog alertDialog = new AlertDialog.Builder(NewSuggestion.this).create();
                alertDialog.setTitle("Alert");
                alertDialog.setMessage("Please choose your reviewer");
                alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                alertDialog.show();
            }else{
                editor.putString("reviewer",spReviewer.getSelectedItem().toString());
                Intent intent = new Intent(NewSuggestion.this,NewSuggestion2.class);
                startActivity(intent);
            }
            editor.commit();
        }
    });

//code for recall from SharedPreferences

SharedPreferences sharedPreferences = getSharedPreferences("MyData", MODE_PRIVATE);
    String title = sharedPreferences.getString("title",DEFAULT);
    String year = sharedPreferences.getString("year",DEFAULT);
    String month =  sharedPreferences.getString("month",DEFAULT);
    String present =  sharedPreferences.getString("present",DEFAULT);
    String details = sharedPreferences.getString("details",DEFAULT);
    String benefit =  sharedPreferences.getString("benefit",DEFAULT);
    String suggestionwill =  sharedPreferences.getString("suggestionwill",DEFAULT);
    String reviewer =  sharedPreferences.getString("reviewer",DEFAULT);

Do not store the image in SharedPreferences, you should save an image to sd-card and then save the image path from sd-card into SharedPreferences ->

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.edit().putString("YourImagePathTag","YourImagePath").commit;

then you can get the image from this path. Also, you can save the path into the database which is safer than this.

Don't save the image using preference, instead use the SQLite for saving and retrieving by use "blob"

//Convert your bitmap to base64

public static String encodeBitmapTobase64(Bitmap image) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.PNG, 100, os);
    byte[] byteArray = baos.toByteArray();
    String encodedImageString = 
    Base64.getEncoder().encodeToString(byteArray);
    return encodedImageString ;
}

//Save the image in preferences

SharedPreferences.Editor prefEditor= myPrefrence.edit();
prefEditor.putString("key", encodeBitmapTobase64(yourbitmap));
prefEditor.commit();

// get encoded string from pref and convert base64 string to bitmap

public static Bitmap base64ToBitmap(String encodedString) {
    byte[] decodedString = Base64.decode(encodedString, Base64.DEFAULT);
    Bitmap bitmap= BitmapFactory.decodeByteArray(decodedString , 0, 
    decodedString.length);
    return bitmap;
}

saving the image in the sharedpreference(by string) is not a good method. make the image to the bytearray or uri(after save in the EXTERNAL_STORAGE) and use the intent.putextra

When you're getting the selected image for example from gallery in onActivityResult() method then you can save the path string from Uri like this:

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

    // Result code is RESULT_OK only if the user selects an Image
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
            case GALLERY_REQUEST_CODE:
                //data.getData returns the content URI for the selected Image
                Uri selectedImage = data.getData();

                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
                sharedPreferences.edit().putString("KEY_IMAGE", selectedImage.getPath()).apply();
                break;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM