Get string from sharedpreference, convert to bitmap, display in imageview - android

I am converting my image to string and storing that string in sharedpreferences. then later on other activity I want to fetch that string convert back to bitmap and display it in image view. Also for precausion if nothing is fetched from sharedpreference I would like to set ic_launcher as default image in my ImageView.
THis is how i am trying to get above task done.
String pic = shared.getString("UserPic","");
Log.i("picstring-verifydetail" , "picstring : "+pic);
if (pic != null && pic != "") {
try {
userpic = ImageHelper.stringToImage(pic);
profilepic.setImageBitmap(userpic);
} catch (IOException e) {
Log.e("picsetting", e.toString());
e.printStackTrace();
}
}
else
{
Bitmap defaultImage = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
profilepic.setImageBitmap(defaultImage);
}
I have also stored some values like name and that are successfully fetched but string for image is not getting fetched from sharedpreferences. It is always going to else part and there again I am getting error : "Source not found" on profilepic.setImageBitmap(defaultImage);. I searched logcat but found no error.
Please help to achieve these 2 task.
Thanks & Regards,
Sourabh Gupta

I don't think what you are trying to do is a good idea.
Try to save the image in SD card or Internal Storage and just store the File path in SharedPreferences.

If you have these images stored in assets OR res folders. You can just store the image names into the SharedPreferences and later you can fetch the image names from it and display on the screen by fetching them from the path.

Related

Error while fetching the full path name of an image in Android

In order to send an image to server, while getting the path of the image , the following code is used
private String getPath(Uri uri){
String path = null;
Cursor cursor = null;
try {
Toast.makeText(this,"Beginning of getPath()", Toast.LENGTH_LONG).show();
cursor=getContentResolver().query(uri,null,null,null,null);
cursor.moveToFirst();
String document_id=cursor.getString(0);
document_id=document_id.substring(document_id.lastIndexOf(".")+1);
cursor=getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,null,MediaStore.Images.Media._ID+"=?",new String[]{document_id},null);
cursor.moveToFirst();
path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
Toast.makeText(this,"At the end of getPath()", Toast.LENGTH_LONG).show();
}
catch(Exception e){
e.printStackTrace();
} finally {
cursor.close();
}
return path;
}
I have set two toast methods here to check the flow of control. I'm getting the first toast message at the beginning of the method but not getting the next one...which reflects the error in the that part of the code...
What might have gone wrong here.
Android stack trace gave the following'
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at the folowing line
path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
In order to send an image to server, while getting the path of the image , the following code is used
That code will not work for arbitrary Uri values.
What might have gone wrong here
You are trying to derive a file path for a Uri.
Use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. Then, either:
Use the InputStream directly for uploading the content, if your HTTP client API supports that, or
Use the InputStream and a FileOutputStream (on some file that you control, such as in getCacheDir()) to make a copy of the content. Then, upload the copy, deleting the copy when you are done.

Compare one image with other images stored in the sdcard

How to compare one image token with camera with all the other images stored in the sd card and display the result?
public class SearchForFaces extends Activity {
Bitmap bitmapOriginale;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b1 = getIntent().getExtras();
String cin= b1.getString("cin");
//getting the image
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/Student");
File file = new File(directory, cin+"jpg");
try {
FileInputStream streamIn = new FileInputStream(file);
bitmapOriginale = BitmapFactory.decodeStream(streamIn);
streamIn.close();
} catch (IOException e) {
Log.d("SearchForFaces Exception", e.getMessage());
}
if(bitmapOriginale.sameAs(//images from sdcard))
{
//display founded image
}
}
}
i think, its not necessary read all images..if you want compare images from camera, you can "easy" take the images in DCMI folder. But ok, user will move some files in another folder. So in that case i will advice just open first folder, read files in there and check the format, after that open another folder, read files in there and again check the formats and save the paths to the jpg files.
So in this case just easy some for, foreach, while cykl or you can do it with recursion.
You will have some ArrayList (linkedList, whatever) and in this list you can put the paths. Then just call your sameAs method.
On this you can use Environment.getExternalStorageDirectory().listFiles();
But..i am not sure if your "algorithm" will work..image recognition is really hard part of computer science..and if you dont know how to get the files on SDcard..the algorithm wouldnt probably work..
But if you want to check the similarity with byte by byte comparsion, then its ok..
Check also this blog http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html It shows how to read an images from sd card. Once you read them you can use your sameAs() written method to compare them.

Can't see image in ImageView android

I am trying to populate ListView Item with an object from MyClass. One of the property of the class is jpg image. I put my images in images/ folder. I use this code for populating
private static final String ASSETS_DIR = "images/";
String imgFilePath=ASSETS_DIR+r.resourceID;
try{
Bitmap bitmap = BitmapFactory.decodeFile(imgFilePath);
resourceIdView.setImageBitmap(bitmap);
}
catch(Exception e)
{
System.out.println(" Error");
}
r.resourceID is the name of the image for example "AUD.jpg"
resourceIDView is ImageView
The program don't get in the catch part, however I can't see the image
could somebody help me??
From your naming convention I conclude that you are storing your images in the "assets" folder. If yes, then you can use the following lines of code and get this issue resolved:
private static final String ASSETS_DIR = "images/";
String imgFilePath=ASSETS_DIR+r.resourceID;
try{
Drawable d = Drawable.createFromStream(getAssets().open(imgFilePath), null);
resourceIdView.setImageDrawable(d);
}
catch(Exception e)
{
System.out.println(" Error");
}
Hope this helps.
put your image in drawable folder and set so imageview...
resourceIdView.setImageResource(R.drawable.AUD);
You can try to put your images in drawable folder under /res. Use an ImageAdapterthat extend BaseAdapterto populate your ListView. You can use this code : http://www.java2s.com/Code/Android/2D-Graphics/extendsBaseAdaptertocreateImageadapter.htm
What I had was that the image was showing in Designer but not on device, so I put the image in all the drawable-xdpi directories. This worked for me.

Get R.drawable ID's dynamically in android

I have a folder with a few images, these images are added by user dynamically. So i need to get the R.drawable ID's of these images in android.... ???
Where are you saving these images too? When images are being added dynamically at runtime usually you need to store them on the phones storage. If you want the images to be stored in the external storage (SDCard) then you can use the following code to retrieve them and add them to your view (Which I assume your doing). This code assumes the images are being stored to your devices SDCard, which is where they will be pulled from.
//Get root directory of storage directory, pass in the name of the Folder if they are being stored farther down, i.e getExternalFilesDir("FolderName/FolderName2")
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
File dir = getExternalFilesDir(null);
Bitmap bmap = null;
try {
InputStream is = new FileInputStream(new File(dir,"image.jpg"));
bmap = BitmapFactory.decodeStream(is);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (bmap!=null) {
ImageView view = new ImageView(this);
view.setImageBitmap(bmap);
}
}

Android Show image by path

i want to show image in imageview without using id.
i will place all images in raw folder and open
try {
String ss = "res/raw/images/inrax/3150-MCM.jpg";
in = new FileInputStream(ss);
buf = new BufferedInputStream(in);
Bitmap bMap = BitmapFactory.decodeStream(buf);
image.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
but this is not working i want to access image using its path not by name
read a stream of bytes using openRawResource()
some thing like this should work
InputStream is = context.getResources().openRawResource(R.raw.urfilename);
Check this link
http://developer.android.com/guide/topics/resources/accessing-resources.html#ResourcesFromCode
It clearly says the following
While uncommon, you might need access your original files and directories. If you do, then saving your files in res/ won't work for you, because the only way to read a resource from res/ is with the resource ID
If you want to give a file name like the one mentioned in ur code probably you need to save it on assets folder.
You might be able to use Resources.getIdentifier(name, type, package) with raw files. This'll get the id for you and then you can just continue with setImageResource(id) or whatever.
int id = getResources().getIdentifier("3150-MCM", "raw", getPackageName());
if (id != 0) //if it's zero then its not valid
image.setImageResource(id);
is what you want? It might not like the multiple folders though, but worth a try.
try {
// Get reference to AssetManager
AssetManager mngr = getAssets();
// Create an input stream to read from the asset folder
InputStream ins = mngr.open(imdir);
// Convert the input stream into a bitmap
img = BitmapFactory.decodeStream(ins);
} catch (final IOException e) {
e.printStackTrace();
}
here image directory is path of assets
like
assest -> image -> somefolder -> some.jpg
then path will be
image/somefolder/some.jpg
now no need of resource id for image , you can populate image on runtime using this

Categories

Resources