How to store images using SharedPreference in android?
Its not recommended to store image in Share preferences And you should store that image to sdcard.And then store image path (from sdcard) into Share preferences like this--
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit=shre.edit();
edit.putString("imagepath","/sdcard/imh.jpeg");
edit.commit();
and then fetch image from sdcard by using this path
How to save Image in shared preference in Android | Shared preference issue in Android with Image
I solved your problem do something like that:
Write Method to encode your bitmap into string base64-
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}Pass your bitmap inside this method like something in your preference:
SharedPreferences.Editor editor = myPrefrence.edit();
editor.putString("namePreferance", itemNAme);
editor.putString("imagePreferance", encodeTobase64(yourbitmap));
editor.commit();And when you want to display your image just anywhere, convert it into a bitmap again using the decode method:
// method for base64 to bitmap
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}Please pass your string inside this method and do what you want.
How to save cropped image uri in shared Preference
Wrote this based on the link I provided earlier...
...
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_IMAGE) {
Bundle extras = data.getExtras();
Uri filePathFromActivity = (Uri) extras.get(Intent.EXTRA_STREAM);
filePathFromActivity = Uri.parse(getRealPathFromUri( (Activity) CurrentActivity.this, filePathFromActivity));
imagePath = filePathFromActivity.getPath();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("imagePath", imagePath);
// Commit the edits!
editor.commit();
}
}
...
public String getRealPathFromUri(Activity activity, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Flutter & Shared Preference : How do I save a network image to local memory?
Your image might be too big for the following method so I'm using a smaller placeholder image from https://picsum.photos/200 that returns a random image everytime it is called. Review the following code that first checks if image is saved in Shared Preferences, if not, the code will download the image, convert the image to base64 string and save the image base64 string to Shared Preferences.
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State createState() => MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> {
String _base64;
Future getImage;
Future<String> _getImage() async {
String base64;
final SharedPreferences prefs = await SharedPreferences.getInstance();
base64 = prefs.getString("base64Image");
if (base64 == null) {
final http.Response response = await http.get(
'https://picsum.photos/200',
);
base64 = base64Encode(response.bodyBytes);
prefs.setString("base64Image", base64);
}
return base64;
}
@override
void initState() {
super.initState();
getImage = _getImage();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Example App')),
body: FutureBuilder<String>(
future: getImage,
builder: (context, snapshot) {
if (snapshot.hasData) {
_base64 = snapshot.data;
final Uint8List bytes = base64Decode(_base64);
return ListTile(
leading: Image.memory(bytes),
title: Text(_base64),
);
}
return const Center(child: CircularProgressIndicator());
},
),
);
}
}
How to store an image using sharedpreferences? Android
If you want to use sharedPreferences, use the below code:
SharedPreferences sharedPreferences;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("data", context.MODE_PRIVATE);
//Adding the picture bit
imgButton = (ImageButton) 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);
}
});
if(sharedPreferences!=null)
String path = sharedPreferences.getString("path", null);
if(path!=null)
imgButton.setImageBitmap(BitmapFactory.decodeFile(path));
}
@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) {
Uri SelectedImage = data.getData();
String[] FilePathColumn = {MediaStore.Images.Media.DATA };
Cursor SelectedCursor = getContentResolver().query(SelectedImage, FilePathColumn, null, null, null);
SelectedCursor.moveToFirst();
int columnIndex = SelectedCursor.getColumnIndex(FilePathColumn[0]);
String picturePath = SelectedCursor.getString(columnIndex);
SelectedCursor.close();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("path", picturePath);
editor.commit();
// Drawable d = new BitmapDrawable(getResources(),BitmapFactory.decodeFile(picturePath));
// btnOpenGalery .setImageBitmap(d);
imgButton.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Toast.makeText(getApplicationContext(), picturePath, Toast.LENGTH_SHORT).show();
}
}
Related Topics
Httpurlconnection Worked Fine in Android 2.X But Not in 4.1: No Authentication Challenges Found
Android Studio Getslotfrombufferlocked: Unknown Buffer Error
Which Can Replace Capturepicture Function
How to Link a Prebuilt Shared Library to an Android Ndk Project
Android Studio: Gradle: Error: Cannot Find Symbol Variable
Why "This App Has Been Built with an Incorrect Configuration" Error Occured in Some Phones
View the Task's Activity Stack
Nexus 7 Not Visible Over Usb via "Adb Devices" from Windows 7 X64
Android-L Cardview Visual Touch Feedback
How to Check Google Play Services Version
How to Select Multiple Images from Gallery in Android
Android How to Runonuithread in Other Class
Listen to Own Application Uninstall Event on Android
Android: Detect Orientation Changed
Android Intent.Getstringextra() Returns Null
Unzip a Zipped File on Sd Card in Android Application
Using Build Types in Gradle to Run Same App That Uses Contentprovider on One Device
How to Retrieve Key Alias and Key Password for Signed APK in Android Studio(Migrated from Eclipse)