Setting image variable in fragments - android

Sorry, I'm still a beginner in coding, but how do I make this code work? actor art is a variable I have from an array.
And it's the name of a image I have in my drawable. This line of code works on any activity type but not on fragments. How do I set image from a variable from an array?
int imageId = AppUtil.getImageIdFromDrawable(this, actorart);
ImageView ivCoverArt = view.findViewById(R.id.imgactor);
ivCoverArt.setImageResource(imageId);
The error for this is that this cannot be used.
This also doesn't work:
ImageView imageView= view.findViewById(R.id.imgactor);
imageView.setImageResource(actorart);
The error here is that actorart is a String but setImageResource is an action for an int.

You are correct, setImageResource() takes in an integer, more specifially the ID of the resource.
To get the ID, you can use the following:
int id = getResources().getIdentifier("yourpackagename:drawable/" + actorart, null, null);

this cannot be used cause the instance you are refering with this is a Fragment, and I'm pretty sure you need a Context parameter.
To fix it get a valid Context:
int imageId = AppUtil.getImageIdFromDrawable(getActivity(), actorart);

Related

How to change an ImageView with a filename

I have a string with the name of the file that I want (R.drawable.square) to put in the imageview.
String shape = "square"
I am trying to use the method below to show the image
imageView.setImageResource()
Hardcoding the filename in works but I want to be able to pass different filenames in.
image.setImageResource(R.drawable.square)
tl;dr
can't get from String:"square" to int:R.drawable.square
Please see Android, reference things in R.drawable. using variables?
//to retrieve image in res/drawable and set image in ImageView
String imageName = "picture"
int resID = getResources().getIdentifier(imageName, "drawable", "package.name");
ImageView image;
image.setImageResource(resID );
I achieved the effect by putting the images in the assets directory
I think it's better to use you Strings as key and your resource ids as value in a Map Object.
Map<String, Integer> resources = new HashMap<>();
resources.put("square", R.drawable.square);
// resources.put("...", R.drawable....);
imageView.setImageResource(resources.get("square"));

Loading image dynamically from drawer crashing the app

I am very new to android. I have to load images dynamically in to recycler view row. I am using the following code and application get crashing due to null object.
String uri = "#drawable/menu_howtouse";
int imageResource = this.context.getResources().getIdentifier(uri, null, this.PACKAGE_NAME);
Drawable res = this.context.getResources().getDrawable(imageResource);
holder.iconImageView.setImageDrawable(res);
The crash could be because the context is null.
Try this code,
int imageResource = this.context.getResources().getIdentifier("menu_howtouse", "drawable", this.PACKAGE_NAME);
Make sure you have initialized holder.iconImageView as follows,
holder.iconImageView = (ImageView) convertView.findViewById(R.id.iconImageView);
The second parameter can be null, but you shouldn't need to set that.
You should be able to use this
context.getResources().getIdentifier("menu_howtouse", "drawable", this.PACKAGE_NAME);
If anything there is throwing a nullpointer, it is probably the context because those other methods don't throw any exceptions
Is the same image to be added to every row you can do this:
holder.iconImageView.setImageResource(R.drawable.menu_howtouse);
OR
If multiple images form drawable to be added, then make list of all the Drawables
List<int> imageList = new ArrayList<int>();
imageList.add(R.drawable.iamge1);
imageList.add(R.drawable.iamge2);
imageList.add(R.drawable.iamge3);
pass this to adapter class
Adapter adp = new Adapter(context, imageList);
Then in onBindViewHolder do this
holder.iconImageView.setImageResource(imageList.get(position));
-- OR --
you can try Picasso or glide, they are very simple to integrate

Setting ImageView source to an image from SQLite

I have a small SQLite DB in my project, where I have table "Products". One of the columns of this table is String "image". In the activity I receive a product id in the Intent extras, and create a Product object from the DB. In the layout of this activity I have an ImageView. Each time a Product object is created, I want to set the ImageView image to the one that is stored in the object. I tried to do the following:
ImageView product_image = (ImageView) findViewById(R.id.product_image);
product_image.setImageDrawable(Integer.parseInt("R.drawable."+productToPresent.getImage());
productToPresent is my Product object and getImage returns the image string name.
However at this point my app crashes and I'm getting the following error message in the logcat:
RuntimeException: Unable to start activity ComponentInfo{com.myapp.appname/com.myapp.appname.ActivityProductDetails}: java.lang.NumberFormatException: Invalid int: "R.drawable.cat02_prod02"
where cat02_prod02 is the string stored stored in my DB and the filename of the image.
So how can it be done?
You can do it in this manner:
int id = getResources()
.getIdentifier("yourpackagename:drawable/" + StringGenerated, null, null);
This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following
imageview.setImageResource(id);

Access a image dynamically from res folder android

I have a image in res folder like this
I want to access this one dynamically like this
holder.Viewcover.setImageDrawable(Drawable.createFromPath("R.id." + CoverimgUrl.get(position)));
CoverimgUrl is a list which have two image name one is book_cover & and another is blank_image this array is generated dynamically so how can I set this image from that list
In One word how to access a image dynamically which is in drawable folder and I need get that image name from an array list ?
Resources res = getResources();
String mDrawableName = "image_name";
int resourceId = res.getIdentifier(mDrawableName , "drawable", getPackageName());
Drawable drawable = res.getDrawable(resourceId);
icon.setImageDrawable(drawable );
First Make CoverimgUrl list of integer
List<Integer> CoverimgUrl =new ArrayList<Integer>();
CoverimgUrl.add(R.drawable.book_cover);
CoverimgUrl.add(R.drawable.blank_image);
Then
holder.Viewcover.setImageResource(CoverimgUrl.get(position));
createFromPath expects a path to the file, not it's ID.
You can use the following:
int id = getResources().getIdentifier(CoverimgUrl.get(position), "id", getPackageName());
holder.Viewcover.setImageDrawable(getResources().getDrawable(id));
getIdentifier() gets the ID from the string. When you use the "R" class, it contains static integers for ids. So R.id.some_name is actually an integer, which is the id of the some_name resource.
once you get this integer with getIdentifier, you can use getResources().getDrawable() to get the drawable with the given ID.
Let me know if this works.

Can you call a string resource with a string?

I have a method that returns one of about 20 possible strings from an EditText. Each of these strings has a corresponding response to be printed in a TextView from strings.xml. Is there a way to call a string from strings.xml using something like context.getResources().getString(R.strings."stringFromMethod")? Is there another way to call a string from a large list like that?
The only methods I can think of is converting each string to an int, and use that to find a string in a string array, or a switch statement. Both of which involve a huge amount if-else if statements to convert the string to an int, and would take just enough steps to change if any strings were added or taken away that I'd be more likely to miss one and have fun bug hunting. Any ideas to do this cleanly?
Edit: Forgot to add, another method I tried was using was to get the resourceID from
int ID = context.getResources().getIdentifier("stringFromMethod", "String", context.getPackageName())
and taking that integer and putting it in
context.getResources().getString(ID)
That doesn't appear to be working either.
No, you can't. The getString() requires the resource id in integer format, so you can't append a string to it.
You can, however, try this:
String packageName = context.getPackageName();
int resId = context.getResources().getIdentifier("stringFromMethod", "string", packageName);
if (resId == 0) {
throw new IllegalException("Unknown string resource!"; // can't find the string resource!
}
string stringVal = context.getString(resId);
The above statements will return string value of resource R.string.stringFromMethod.
You need to use reflection (pretty ugly but only solution) load the R class, and get the relevant field by you string and get the value of it.
this is what I used to do in these kind of situations, I will made a Array like
int[] stringIds = { R.string.firstCase,
R.string.secondCase, R.string.thridCase,
R.string.fourthCase,... };
int caseFromServer=getCaseofServerResponse();
here caseFromServer varies from 0 to wahtever
and then simply
context.getResources().getString(stringIds[caseFromServer]);

Categories

Resources