Set Image Dynamically In A Listview By Retrieving Image Name From A Data Source In Android
What is the best way to retrieve images from drawable folder while the name of those images are stored in a DB and show them in a listView ? Suppose i have three pictures in drawab
Solution 1:
You can get an image from the drawable folder with a dynamic name this way:
resources.getIdentifier(String imageName, String folder, String package);
This returns an integer the same way you would type
R.drawable.imageName;
An example of how to use it:
Bitmap bitmap[] = new Bitmap[5];
for (int i = 0; i < 5; i++)
bitmap[i] = BitmapFactory.decodeResource(
resources,
resources.getIdentifier("pic" +i, "drawable", "com.example.com")));
This gets images from "pic0.png", "pic1.png" ... until "pic4.png", of course you can customize it the way you want
Solution 2:
int[] resID = newint[2]
String[] mDrawableName=newString[2];
mDrawableName[0] = "pic1";
mDrawableName[1] = "image";
mDrawableName[2] = "another_image";
for(i=0:i<=2:i++)
int resID[i] = getResources().getIdentifier(mDrawableName[i] , "drawable", getPackageName());
Usage
image.setImageResource(resID[0]);
Solution 3:
Ok the problem was that i was assigning my Adapter Layout Parameter wrong. Instead of ListView_Row i was pointing to ListView itself
So:
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.custom_listview, cursor, from, to, 0);
Would be:
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.custom_listview_row, cursor, from, to, 0);
Post a Comment for "Set Image Dynamically In A Listview By Retrieving Image Name From A Data Source In Android"