So in this situation first we have to retrieve the image name from the data source(It can be a SQLite database or any other data source).Store it in a string variable.Note here,we have to store the image name here(not with the extension).So if the data source gives you image name with extension then cut the name from the extension.We need "imageName" here,not "imageName.png".So follow the code below...
try { Class<drawable> res = R.drawable.class; if(str!=null){ Field field = res.getField(str); int drawableId = field.getInt(null); bengalidaypng.setImageResource(drawableId); } } catch (Exception e) { System.out.println("Image not found in drawable folder"); }Here "str" is the string variable that hold the imageName retrieved from a data source.If the image with desired name not found in the project's drawable folder then the "catch" block will execute.Hope it is very easy to understand.Feel free to make a comment if you have a doubt.
thanks :) nice one
ReplyDeleteI used the code but I cant get the image to be shown. Here's the code...
ReplyDeletepublic void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView card1 = new ImageButton(this);
String str = "drawable/b0";
try {
Class res = R.drawable.class;
if (str != null) {
Field field = res.getField(str);
int drawableId = field.getInt(null);
card1.setImageResource(drawableId);
setContentView(card1);
}
} catch (Exception e) {
System.out.println("Image not found in drawable folder");
}
}
What am I missing?
Thanks in advance
Hi, Luiz...
ReplyDeletePlease use String str = "image_name";
not the drawable/b0.Also don't use the extension with the image name.Only the image name without extension is needed here.Thanks...
thanxx code work like:-
ReplyDelete@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView card1 = new ImageButton(this);
String str = "pic_4";
try {
Class res = R.drawable.class;
if (str != null) {
Field field = res.getField(str);
int drawableId = field.getInt(null);
card1.setImageResource(drawableId);
setContentView(card1);
}
} catch (Exception e) {
System.out.println("Image not found in drawable folder");
}
}