How to add an Image to ImageView dynamically from a JSON array - android

I want to add an image to my iamgeview from the link stored in a JSON file that looks like this:
{
"parts":[
{"name": "Bosch Iridium",
...
...
...
"image": "R.drawable-hdpi.plug_boschi"
},
Right now I pull the link and display it with this code:
try {
jObject = new JSONObject(sJSON.substring(sJSON.indexOf('{')));
JSONArray pluginfo = jObject.getJSONArray("parts");
JSONObject e = pluginfo.getJSONObject(position);
String imagefile = e.getString("image");
Drawable image = getDrawable(imagefile);
ImageView itemImage = (ImageView) findViewById(R.id.item_image);
itemImage.setImageDrawable(image);
} catch (JSONException e) {
e.printStackTrace();
}
}
I'm pretty sure that this part is correct
ImageView itemImage = (ImageView) findViewById(R.id.item_image);
itemImage.setImageDrawable(image);
But I need help with the part above that which is getting the link from the JSON array so I can display it.

You need to get first the resource ID from the string contained in the JSON.
String imagefile = e.getString("image");
String resName = imagefile.split("\\.")[2]; // remove the 'R.drawable.' prefix
int resId = getResources().getIdentifier(resName, "drawable", getPackageName());
Drawable image = getResources().getDrawable(resId);

What you want to do is to look at the Resources class.
getIdentifier (String name, String defType, String defPackage);
So, basically parse the object to find the text plug_boschi, and call:
int resid=Context.getResources().getIdentifier ("plug_boschi", "drawable", null);

Related

Android: Enable certain button with id as index

I have 50 styled buttons with identificators like "level_i", I need to enable button with certain i in id.
I have code to work with indexed aarays in string xml, but I have no proper ideas how to change it for my usage
Class<R.id.array> res;
Field field;
try {
res = R.array.class;
field = res.getField("words_" + fname);
//set myString to the string resource myArray[fname,y]
myString = getResources().obtainTypedArray(field.getInt(null)).getString(y);
}
catch (Exception e) {
e.printStackTrace();
}
I believe you are saying that you have an ID resource named "words_" + fname for example R.id.words_100. If that is correct, then you can first get the ID using the name of the resource with getIdentifier. Then you can get the actual ID, then you can find the view with that ID:
String resName = "words_" + fname";
Resources res = getResources();
int resId = res.getIdentifier(resName, "id", getPackageName());
View button = findViewById(resId);
EDIT:
Modified original answer to fetch resources from R.id rather than R.string-array.

Android: How check if a image exists in a IF clause?

I need to know how check if an image exists in R.drawable, It has to be dynamic so I have to use a string that gives me the name of the image.
I've tried with '!=null' or exist but it hasn't worked.... Help please!!!!!!!!!
titulo=bundle.getString("titulo");
textView = (TextView) findViewById( R.id.textView1);
textView.setText(titulo);
foto="f"+bundle.getString("numero")+"a";
System.out.println(foto);
flipper =(ViewFlipper) findViewById(R.id.vfFlipper);
this gives me the name of the image a need...
image = new ImageView(this);
image= new ImageView(this);
image.setImageResource(R.drawable.f00a1);
image.setScaleType(ScaleType.FIT_CENTER);
flipper.addView(image);
Whith this I can use the image but i need to use the variable "foto" so it can be dynamic
Thanks!
Everything in the R class is an integer - you can't create a string to represent a resource id. The closest you can get is to use getResources() then call...
getIdentifier(String name, String defType, String defPackage)
...this will allow you to find the integer which represents your resource based on the resource name.
you could use getResources to get an instance of Resources class. In Resources class, you have getDrawable If the resource is not found, you would get ResourceNotFoundException which also means the image is not found.
so the code will be something like this
Resource r = getResources();
Bool fileFound = true;
Drawable d = null;
try{
d = r.getDrawable(your_image_id);
}
catch(ResourceNotFoundException e){
fileFound = false;
}
if(findFound){
// Your operations
// set drawable to your imageview.
}
Thank you all! i mix the two answers and .. it work!
Resource r = getResources();
Bool fileFound = true;
Drawable d = null;
try{
d = r.getDrawable(getIdentifier(foto1, "drawable", getPackageName());
}
catch(ResourceNotFoundException e){
fileFound = false;
}
if(findFound){
// Your operations
// set drawable to your imageview.
}
getResources().getIdentifier("icon", "drawable", "your.package.namespace");
check for non zero value for above statement.
if(0)
//does not exists
else
//exists
private boolean isDrawableImageExists(String imgName) {
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
return id != 0;
}

Getting Error in android -- the method setImageResource(int) is the type Image View is not applicable for the argument(string)

I am trying to pass image from one activity to another activity using listview item, but I am getting this error line
the method setImageResource(int)
is the type Image View is not applicable for the argument(string) and at this point of line:-
lblImage.setImageResource(Image);
I don't know now what need to write to remove this error please someone support me and write the exact code to be fit on this line, here I am also placing some code for your reference:
SingleMenuItem(Activity to fetch Image with some text data)::
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String title = in.getStringExtra(KEY_TITLE);
String artist = in.getStringExtra(KEY_ARTIST);
String duration = in.getStringExtra(KEY_DURATION);
String Image = in.getStringExtra(KEY_THUMB_URL);
//Bitmap bitmap =(Bitmap) in.getParcelableExtra(KEY_THUMB_URL);
// ImageView image = (ImageView)findViewById(R.id.thumb_url);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
ImageView lblImage = (ImageView) findViewById(R.id.image_label);
//image.setImageBitmap(bitmap);
lblName.setText(title);
lblCost.setText(artist);
lblDesc.setText(duration);
lblImage.setImageResource(Image); //Getting Error at this line only
//the method setImageResource(int) is the type Image View is not
// applicable for the argument(string)
}
}
ActivityCode (to pass image and text data)
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById
(R.id.title)).getText().toString();
String artist = ((TextView) view.findViewById(
R.id.artist)).getText().toString();
String duration = ((TextView) view.findViewById
(R.id.duration)).getText().toString();
// byte[] array = null;
// Bitmap thumb_url = BitmapFactory.decodeByteArray
(array, 0, array.length);
String Image=((ImageView)view.findViewById
(R.id.list_image)).getImageMatrix().toString();
// Starting new intent
Intent in = new Intent
(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_ARTIST, artist);
in.putExtra(KEY_DURATION, duration);
in.putExtra(KEY_THUMB_URL, Image);
//in.putExtra(KEY_THUMB_URL, thumb_url);
startActivity(in);
}
You're passing a String to setImageResource(), which requires an integer.
Resource IDs are actually integers - when you refer in code to R.drawable.myImage this is referring to an integer resource in automatically generated code (R.java) which is created by the compiler.
To load an image from a resource string (not recommended) see Android - Open resource from #drawable String
This will work for image id not for image string
if you want show image in the imageview do it like this:
lblImage.setImageResource(R.drawable.image);
OR
according to your requirement you have to get Drawable from the imag link. by using this code you can get image drawable and then set to image view
public static Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
call this function and the set drawable to image view like this.
Drawable image = LoadImageFromWebOperations(Image); // Image means iamge url getting
from previous activity
imageview.setImageDrawable(image);

dynamically getting all image resource id in an array

there are many images in drawable foder so instead manually creating array of all image resource ids , i want to get all images dynamically of drawable folder in array.
currently i m using this code:
for(int i=1;i<=9;i++)
{
int imageKey = getResources().getIdentifier("img"+i, "drawable", getPackageName());
ImageView image = new ImageView(this);
image.setId(imgId);
image.setImageResource(imageKey);
image.setScaleType(ImageView.ScaleType.FIT_XY);
viewFlipper.addView(image, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
imgId++;
}
but in that code i need to manually edit the image name to get the resource id but i want to get all image with any name..
you can Use Reflection to achieve this.
import the Field class
import java.lang.reflect.Field;
and then write this in your code
Field[] ID_Fields = R.drawable.class.getFields();
int[] resArray = new int[ID_Fields.length];
for(int i = 0; i < ID_Fields.length; i++) {
try {
resArray[i] = ID_Fields[i].getInt(null);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resArray[] now holds references to all the drawables in your application.
Well, If your image names are img1, img2 and so on, then you can create a variable like
String url = "drawable/"+"img"+i;
int imageKey = getResources().getIdentifier(url, "drawable", getPackageName());
you can also replace your getPackageName() method by your package name like "com.android.resource"
Simply,the general function is
public int getIdentifier(String name, String defType, String defPackage)

R.id.image to string in android

In my project I'm trying to display several image files by manipulating the filename of one of the images programatically.
ie, I may have:
filename.jpg, filename_top.jpg, filename_middle.jpg
I receive input of an drawable int and am trying to find the filename of the displayed image before manipulating this filename and trying to display the programatically generated filenames.. problem is that the manipulated filename does not display.
ie. there is something wrong with this:
imageView2.setImageResource(getImageId(this, namebottom));
Any ideas how getImageId can be modified to make setImageResource work properly?
The code would look something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bun = getIntent().getExtras();
int imagenumber = bun.getInt("imagenumber");
String extension = bun.getString("extension");
// int become a val from 0 to 20 (array size)
setContentView(R.layout.clickeditem);
final int[] imgIds = new int[{
R.drawable.image0,R.drawable.image1,R.drawable.image2,,,R.drawable.image20};
//The first image with id top in the layout is set ok:
ImageView imageView1 = (ImageView)findViewById(R.id.top);
imageView1.setImageResource(imgIds [ imagenumber ] );
// problem here:
//try to get the name of this file: ie: filename.jpg
// and then manipulate the filename:
String name = imageView1.getResources().getString(R.id.image0);
//try to convert this to the filename_middle.jpg
String namemiddle = name.replace(".jpg", "_middle.jpg");
imageViewt.setImageResource(getImageId(this, namemiddle));
//try to convert this to filename_bottom.jpg
String namebottom = name.replace(".jpg", "_bottom.jpg");
imageView2.setImageResource(getImageId(this, namebottom));
}
//where getImageId is defines as follows:
public static int getImageId(Context context, String imageName)
{
return context.getResources().getIdentifier("drawable/" + imageName,
null, context.getPackageName());
}
return context.getResources().getIdentifier("drawable/" + imageName,
null, context.getPackageName());
replace this by
return context.getResources().getIdentifier(imageName,
"drawable", context.getPackageName());

Categories

Resources