I have 8 different plant species images under assets folder, I cached the 8 images assets filename (corresponding to the path, E.g foxtail.png, orchid.png) in the assets directory in a database. (Plus other information)
I'm 'displaying the 8 plants in a RecyclerView. Clicking on any of the plants opens the Detail Activity. (Passing the image filename as saved in the asset folder E.g foxtail.png)
How do i pick the specific image file in the assets folder that matches the file name that was passed to Detail Activity and set it to an ImageView??
You can:
Open the file as a stream
InputStream imageStream = null;
try {
// get input stream
imageStream = getAssets().open("foxtail.png");
// load image as Drawable
Drawable drawable= Drawable.createFromStream(imageStream, null);
// set image to ImageView
image.setImageDrawable(drawable);
}
catch(IOException ex) {
return;
}
Finally remember to close the stream with
if(imageStream !=null){
imageStream.close();
}
or
moving your images in the res/drawable folder you can load the images with:
String yourImageName = getImageNameFromDB();
int resId= getResources().getIdentifier(yourImageName, "drawable", "com.example.yourpackegename.");
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(resId);
or
with something like this (always with the images into res/drawable):
private enum Plant {
foxtail, orchid, xyz;
}
String value = getPlantFromDB();
Plant plant = Plant.valueOf(value); // surround with try/catch
switch(plant) {
case foxtail :
resId= R.drawable.foxtail
break;
case orchid :
resId= R.drawable.orchid
break;
default :
resId= R.drawable.xyz
break;
Drawable drawable = getResources().getDrawable(resId);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(drawable);