Sunday, January 23, 2011

How to get images dynamically


Lets say you're storing items in a slqite db for your new, soon-to-be-award-winning application, and one of the columns you're storing is the name of the image to associate with that item.

How on earth do you reference it from within your app so you can display it?
Good question! Here's how:


//first get a reference to the ImageView in our XML layout file we want to display the image in..

ImageView imgVw = (ImageView) customView.findViewById(R.id.imgVwInXML);

//Next check that there is actually an image file name in the db column:

if (OurDBCursor.getString(OurDBCursor.getColumnIndex("imageName")) != null) 
{
 
//if there is a name for the image, get that name..

  myImageName  = OurDBCursor.getString(OurDBCursor.getColumnIndex("imageName"));  
 

//get a reference to the image (located in our drawable folder in our project):
          
  int resID = getResources().getIdentifier("com.BlueMongo.Test:drawable/" + myImageName, null, null);  
 

//assign the resouce with that ID to our ImageView:
               
  imgVw.setImageResource(resID);
}

.. And that's it.

Hope that helps. Have a great day.