Open a resource file just with specific String variable - java

Sorry for the title, had troubles describing what I'm trying to do. I've always had this question for Java as a whole, but right now, its specific for Android. Let's say that I am parsing an API and get this special String, let's say "clear". Inside my drawables, I have a clear.jpg that I would like to set as an ImageView programically . That's not the hard part. What I was wondering is if there was a quick way where I Could call on the .jpg with just the variable name? I know I can easily make different if statements, such as:
if(string == "clear")
{
//setImageView to drawable/clear
}
but is there anyway I can do something such as
//setImageView to drawable/string
where string would be clear? I know obviously it would look for a string inside drawable, but is there anyway I could do what I'm describing? Just a general question I had; it was something I always wondered about.
Let me know! Thanks!

private void showImage() {
String uri = "drawable/icon";
// int imageResource = R.drawable.icon;
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
ImageView imageView = (ImageView) findViewById(R.id.myImageView);
Drawable image = getResources().getDrawable(imageResource);
imageView.setImageDrawable(image);
}
Else I would recommend you to work with R.* references like this:
int imageResource = R.drawable.icon;
Drawable image = getResources().getDrawable(imageResource);
Reference -> Android - Open resource from #drawable String

With what i know, the quickest way to call up that picture is putting the
picture's name in the xml file; For instance if you want to change the background
of an imageview, you can just put in your xml file this code below
android:background="#drawable/clear".
Note the image must have been in the drawable folder. Thanks, i hope this helps.

It looks like Java 8 provides limited support for local variable annotations, but its reflection API can't give you access within method bodies. So you'd need to parse the class file itself. And for that, a library like ASM would do the trick.

if(string.equals("clear")){
int resID = getResources().getIdentifier("clear", "drawable", getPackageName());
imageView.setBackgroundResource(resID);
}

Same as other ones at the point which is using getIdentifier method.
imageView.setImageView(getResources().getIdentifier(string, "drawable",
getPackageName()));
However, by doing this, you can process without if-condition block and just specify a Drawable of the value from string directly (I think it is your intention of this question).

Related

is it possible to get mipmap image by id?

I have stored image icons in res/mipmap folder of my android project. Each of them have their own image id. I want to check if I have image there by image id. I want to do something like,
String input_id = "blue_image";
ImageView image;
if (image.getImageByID(input_id)){ ## if image with blue_image exists
image.setImageResource(...);
}
If I know that blue_image exists then I usually get it like
image.setImageResource(R.mipmap.blue_image);
There seems to be 2 problems in this question. One is about checking image exists by ID and second one is to find something similar to getattr() python function in java.
If you have any other solutions to similar case, those are also welcome.
Try this in your Activity class:
int imageId = getResources().getIdentifier(inputId, "drawable", getPackageName());
if (imageId > 0) {
image.setImageResource(imageId);
}
The point is that getIdentifier() returns 0 if no resouce was found.
Use:
int imageId = getResources().getIdentifier(inputId, "mipmap", getPackageName());
With "mimap", not "drawable" as the other answer suggests

Using a String variable to dynamically add SVG to ImageView

Basically, I'm trying to add an SVG drawable to an ImageView, but I keep getting strange type errors I can't resolve.
// String var "icon" holds the name of the drawable resource
int drawableId = context.getResources()
.getIdentifier(icon, "drawable", MainActivity.PACKAGE_NAME);
// drawableId shows the error:
// 'getDrawable(android.content.Context, int)' in 'android.support.v4.content.ContextCompat' cannot be applied to '(int)'
// I tried using Context instead of ContextCompat, but I got an error about needing API 21
Drawable channelIcon = ContextCompat.getDrawable(drawableId);
// drawableId here shows no error
imageView.setImageResource(drawableId);
Any idea what I'm doing wrong? Basically this is a workaround for needing to use a variable for R.drawable.something
Thanks.
I'm trying to add an SVG drawable to an ImageView
ImageView does not support SVG.
Any idea what I'm doing wrong?
Beyond the aforementioned issue, replace:
Drawable channelIcon = ContextCompat.getDrawable(drawableId);
with:
Drawable channelIcon = ContextCompat.getDrawable(context, drawableId);

How to use an image in a java project without an absolute path

I've been working in a little project to get a bit of practice programming. It's basically done, but I won't be satisfied until I can use images properly, a bit of help would be appreciated.
So, currently I'm using the the getImage method from the ImageIcon class, like so:
Image body = new ImageIcon("C:/Users/Centollo/Documents/NetBeansProjects/Chess/build/classes/chess/img/WhiteBishop.png").getImage();
I've been trying to figure out how to do the same thing without using an absolute path, but I don't know how to make the images a part of the jar so that it works fine in any other machine.
All I need to know is where to put the images and how would the code to access them look like.
Try to explain it like I'm stupid, please. I've read answers to similar questions but I can't make heads or tails of them.
I'm working in NetBeans with a "chess" package with all the .java and a "chess.img" package with all the .png.
If your class extends from JFrame, you can do this:
Image image = new ImageIcon(this.getClass().getResource("/images/MyImage.jpg")).getImage();
If your class extends Applet, you can go this way:
private URL base = null;
private Image myImage = null;
try
{
base = getDocumentBase();
} catch (Exception e)
{
e.printStackTrace();
}
myImage = getImage(base, "images/MyImage.jpg");
A very quick google search yields this:
URL resource = getClass().getClassLoader().getResource( "img/WhiteBishop.png" );
Image body = new ImageIcon( resource );
There are a couple ways to do this but here's the way I would suggest:
Make sure the chess.img folder is in your application's classpath. Then try referring to the path like chess.img/image (yes, you can use forward slash in windows.)
If that doesn't work use:
ChessClass.class.getClassLoader().loadResourceAsStream("/chess.img/image");
Note the forward slash at the beginning of the file reference. This points to the root of the classpath. It's a bit confusing as someone with unix/linux experience might think it refers to the root of the file system. This tends to work better than the other answer given for reasons I knew 10 years ago. This is an ugly bit of Java that was never quite cleaned up.

An alternate way to display images on an android app

I have my ImageView laid out in an .xml file and in my main java file I am using the code
static int[] images = { R.drawable.green_0, R.drawable.blue_1,
R.drawable.purple_2, R.drawable.pink_3, R.drawable.red_4,
R.drawable.yellow_5, R.drawable.white_6, R.drawable.teal_7,
R.drawable.babyblue_8, R.drawable.lightgreen_9,
R.drawable.magenta_10, R.drawable.grey_12, R.drawable.black_11 };
to display images. However, later in the code I am trying to use the line
holder.image.setImageBitmap(images[position].getImage());
which gives the error
"Cannot invoke getImage() on the primitive type int"
How else can I display images in my app to use that line of code with no errors (not declaring the images as boolean type int).
Your problem is that you are working with integer values.
You need to transform this int in Drawable, or Bitmap like this:
holder.image.setImageResource(images[position])
or
holder.image.setImageDrawable( getResources().getDrawable( images[position] ));
or
holder.image.setImageBitmap(BitmapFactory.decodeResource(getResources(), images[position]));
setImageBitmap() takes in a Bitmap object, not an int. The int you are supplying is just the id in the R.java generated resources file.
Use BitmapFactory.decodeResources():
holder.image.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), images[position]));

Android and getting a view with id cast as a string

In the Java code of an Android project if you want the reference for a view resource you can do something like:
View addButton = findViewById(R.id.button_0);
In the above R.id.button_0 is not a String. Is it possible to dynamically refer to a resource by a string, such as "R.id.button_0"?
I'd like to refer to a button by "R.id.button_%i" where %i is replaced by some valid index.
int resID = getResources().getIdentifier("button_%i",
"id", getPackageName());
View addButton = findViewById(resID);
where %i is replaced by some valid index.
The getResources() method belongs to the Context class, so you can use that directly from an Activity. If you are not inside an activity, then use a context to access: (myCtxt.getResources()).
You could try putting all the ids you want in an array and then using that array to dynamically refer to your resources instead.

Categories

Resources