Using string from Cursor to get drawable to ImageView - android

I have a database with string names and string filenames that I am using to dynamically create a page. On the previous page based on the button selected the cursor returns the specific entry needed, and then that is used to find and display the corresponding image. I've been trying to mish-mash code from different places, but nothing seems to be working. It currently looks like this:
ImageView iv = (ImageView) findViewById(R.id.iv1);
Bitmap bmap = (Bitmap) BitmapFactory.decodeResource(this.getResources(),
getResources().getIdentifier(c.getString(4), "drawable", getPackageName()));
iv.setImageBitmap(bmap);
For debugging purposes I've had the cursor getString(4) toasted and it comes out correctly as "al_0" or what it should be, and there is a file in the "drawable" folder in res named "al_0.jpg".
I've tried various combinations of concatenating the packagename and drawable folder location directly with the image name, and putting null in the other variable positions. Each time either I get a crash with a reference to the decodeResource line or that the "No package identifier when getting value for resource number 0x00000000."
Any help would be appreciated, and if more specifics are needed I can try to provide them.
Update: So it seems like something else is wrong, using even the following I get a crash:
ImageView iv = (ImageView) findViewById(R.id.iv1);
iv.setImageResource(R.drawable.al_0);
and R.drawable.al_0 is definitely a correct resource in drawable-mdpi (I moved it by a suggestion from Lint).

Here is what I do.
Store the filename in the format com.example.appname:drawable/filename Notice the colon between appname and drawable.
Then after I pull that string from the database I use this, where imageString is the string from the cursor.
imageResource = ClassName.this.getResources().getIdentifier(imageString, null, null);
imageView.setImageResource(imageResource);

So it turns out everything was completely fine, my images were just to large. Using BitmapFactory.Options.inSampleSize I was able to get everything working fine. Thanks for the helpful debugging tips, I apologize for the mishap.
Update: I also needed to bmap.recycle() as these views were being dynamically created, and they were causing memory errors after a few were opened. Both worked out as being optimal solutions to the problem.

Related

Use dynamic filename in Android R.drawable.<filename>

I'm trying to dynamically construct the filename of an image in Android to use in the R.drawable. clause.
Here's my code:
imgHouse = (ImageView)findViewById(R.id.imageView);
strHouseNameImageFile = strHouseName + ".png";
imgHouse.setBackgroundResource(R.drawable.<filename>);
And in the last line above, I really want it to be a combination of the house name and .png but I'm not sure how to put a string together that will be used by R.drawable.
Could I do something like this for the last line, which now gives an error in Android Studio:
imgHouse.setBackgroundResource(strHouseNameImageFiles);
Any help would be appreciated.
Thanks
int iconResId = getResources().getIdentifier(strHouseName, "drawable",getPackageName());
imgHouse.setImageResource(iconResId);
The way you are trying to set the background resource may not work since the R class is generated at compile time. The R.drawable.*** is really an integer which is generated at compile time. The closest match to your problem may be this post : Dynamic loading of images R.Drawable using variable

Saving resources path in SQLite

I need to save the images in my resource folder in an SQLite database. This database is pre-loaded(copied to data/ path) so the there is no populating at runtime. I've tried to save it like this in text fields in SQLite: "R.drawable.picture1".
There are about 300 small size pictures(jpg) in my drawable folder. When I run the a query ofcourse the cursor returns the particulair string. Now I need to set this as ImageResource on an ImageView, but whatever I try it doesn't seem to work.
I've tried parsing it to an int, what doesn't seem to work. Whatever I try logcat keeps telling me R.id.picture1 isn't a valid integer. I've seen a possible solution some time ago, but I've searched for it all day but can't seem to find it.
What I dont want: Convert the images to byte arrays so I can save it as a blob. I just need a way to store and retrieve an drawable reference that I can use to set the drawable on the ImageView.
I'm not that experienced so I hope someone can help me out.
If you have the name of the resource you can lookup the resource identifier and use that for your ImageResource.
int resId = context.getResources().getIdentifier("picture1","drawable",context.getPackageName());
image.setImageResource(resId);;

need android listview to display drawable png image from text name stored in sqlite database

I've tried answers from other similar stackoverflow questions, but cannot figure out what i am doing wrong. I have an sqlite database which includes several columns, one of which is the filename of a png file stored in res/drawable. I can populate my listview with a list of items from sqlite, and on click i can display all the details stored for that chosen item - EXCEPT that the image never displays. If i simply display the name of the image file, it displays the correct name for that chosen item. But i cannot get the image itself to display.
If I hard-code the image src file into the layout xml, it displays correctly, but, i need to be able to change the image depending upon which item is selected.
Here are three ways I have tried to accomplish this (with a hard-coded name for example simplification using my res/drawable/acorn.png file). None of these works. All the rest of the correct item detail info displays, but no image. Any ideas what i am doing wrong here?
The layout xml includes:
<ImageView
android:id="#+id/wordimage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:maxWidth="200dp"
android:maxHeight="200dp"
android:scaleType="center"
android:contentDescription="image for this word"
/>
attempt 1:
int imageid = getResources().getIdentifier("com.brohoward.androidapps.itzadatabase:drawable/acorn.png", null, null);
ImageView imagenow = (ImageView) findViewById(R.id.wordimage);
imagenow.setImageDrawable(getResources().getDrawable(imageid));
attempt b:
int imageid = getResources().getIdentifier("com.brohoward.androidapps.itzadatabase:drawable/acorn.png", null, null);
ImageView imagenow = (ImageView) findViewById(R.id.wordimage);
imagenow.setImageResource(imageid);
attempt c:
ImageView imagenow = (ImageView) findViewById(R.id.wordimage);
imagenow.setImageBitmap(BitmapFactory.decodeFile("com.brohoward.androidapps.itzadatabase:drawable/acorn.png"));
thanks in advance!
Don't include the .png in the call to getIdentifier:
int imageid = getResources().getIdentifier("com.brohoward.androidapps.itzadatabase:drawable/acorn", null, null);
Then, set the ImageView using ImageView#setImageResource:
ImageView imagenow = (ImageView) findViewById(R.id.wordimage);
imagenow.setImageResource(imageid);
I would start by verifying whether or not getResources().getIdentifier() is returning the correct resource ID. Compare what is returned to the resource ID that is generated for the image in R.java.
If the resource ID is correct, try this:
Bitmap bmpWord = BitmapFactory.decodeResource(getResources(), imageid);
imagenow.setImageBitmap(bmpWord);
If the resource ID is not correct, then that is your problem.

how to include images into an android project best possible manner?

My android app is basically a simple one where there is one listview with 40 list items. And each of those items when clicked leads one to an image. so there are 40 images.
I can always of-course place those images in the res/drawable folder and refer to them directly from my java file in which case there will be hardcoding done
img.setImageResource(R.drawable.day1);
.
.
.
img.setImageResource(R.drawable.day3);
.
.
.
etc.
Is there anyway (by storing the names of the images in an xml for example) to programatically retrieve the image names from folder and display them ?
int resID = getResources().getIdentifier("day" + i,
"id", getPackageName());
where i is your index
img.setImageResource(resID);
Create dynamic bitmap object using resource.
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/"+"test"+index+".png");
image.setImageBitmap(bMap);
Used same name of image like, image1,image2...
call using for loop or index..
What I would do:
I'd place the images in the res/drawable folder as you said, but wouldn't call them like you said; too much work! Try creating an array "Images", filled with a for loop where you add on each position something like:
for (i;i<x;i++) //Where x is the number of images you use
Images[i] = "R.drawable.day"+String.valueOf(i);
// Even you could try with:
// Images[i]="img.setImageResource(R.drawable.day"+String.valueOf(i)+")";
Like this, you just have to call images[i] to call image "i"
I hope this helps you :)
A simple manner to do this is like this:
You place your images in res/drawable, name all using a certain pattern (for instance: img1, img2, img3 ... ) and after that you load them dynamically using a pattern for names like this:
String imageName =IMAGE_PATTERN+id;
int imageResource = getResources().getIdentifier(imageName,null,getPackageName());
imageView.setImageDrawable(getResources().getDrawable(imageResource));
where
IMAGE_PATTERN may be something like "image" or "img" or whatever you used to name your files :)
good luck,
Arkde

Android Bitmap syntax

I want to load bitmaps into ImageViews in Android, but I don't want to use the R.drawable syntax because I have a lot of images with a standard naming convention so it's much easier to get the image with some logic. For example, all my images are named:
img1.png
img2.png
img3.png
So if a user selects a value, let's say x, I show "img" + x + ".png" in the ImageView. Looks like Bitmap.decodeFile is what I need, but I need to know the syntax of how to get to my drawables folder since that's where the images are. Or if there's perhaps a better way.
I realize I could do this with a switch statement instead of concatenating the image name but that would be a lot of lines since I have so many images.
One alternative is to use reflection to load images from R. You can looking static variables by string name. Keep in mind that reflection can be slow though. If you are going to be loading the same image multiple times, you might want to keep a cache of name -> R id.
Edit:
You can also access them by URI. See referring to android resources using uris.
The R.drawable value is a number by itself. You just need to use the first image id and add a fixed value to find the right image. For example:
R.drawable.image1 = 1234;
R.drawable.image2 = 1235;
etc.
So to get image 2 I would to R.drawable.image1 + 1.
Every time the R.java file is regenerated the numbers may change but the sequence will be the same. If you don't want to depend in this then you will have to look at the "assets" folder.
Looks like I've found a solution. The real problem is that I generate the resource names at runtime, but I can get the resource id like this:
getResources().getIdentifier("string1" + string2, "id", "com.company.package")
I can then pass that value to setImageResource or any other method that accepts a resource id.

Categories

Resources