set image with setImageResource in Android Studio using a variable - java

I am trying to set my image in my ImageView through a variable (item is the variable name, which I will be setting to lowerCase).
However, it is not working and resID will return 0.
Here is my code:
ImageView iv = (ImageView)v.findViewById(R.id.imgView);
if (item != null) {
Log.i("item: ", item.toLowerCase());
int resID = getResources().getIdentifier(item.toLowerCase(), "drawable", "package.name");
Log.i("resid: ", String.valueOf(resID)); //will return 0 - im guessing this is where the problem is
iv.setImageResource(resID);
}
I used this as a guide Android, reference things in R.drawable. using variables? but none of the other solutions work for me, in fact they all gave me the same result (returning 0).
I can provide more code if needed (just didn't want it to be bombastic).
Thanks in advance!

getIdentifier() Returns 0 if no such resource was found. (0 is not a valid resource ID.)
and you should getPackageName() method of the context object which always return the correct package name.
if you will show your folder stracture and file's names i can help you to fix it.
btw, if you can get the drawable directly from the resource you can just use R.drawable.resName

Related

Error Correction for findViewById() - What's the return value?

I'm receiving several space names which I save in my variable "space", I then need to change visibility for that space image, but if that image space does not exist then it just continues.
What I want to do is something like this:
ImageView greenball = (ImageView)findViewById(resgreenball);
if(greenball != NULL) /* <---- ERROR HERE*/
greenball.setVisibility(View.VISIBLE);
The compiler gives me an error when trying to compare greenball with NULL.
How can I manage this?
Because not all "space"s I receive are an imageview, just some of them.
Thanks!

Image Resource Gives 0 in Android

I am developing a small online shopping application in Android which needs to have lot of items images, I have a web service which gives the path of image present in android drawable-mdpi, My problem here that I tried this code to get the imageresource id, but it always gives me 0.
String uri = "#drawable/bangle1.png";
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Is there any method, to get resource id, so that I can use it for drawable like :
Drawable res = getResources().getDrawable(imageResource);
I tried googling but most of them suggested the above method and this gives me always 0 value. Any one please help here.
It will be better to get your images into /assets/ folder, and don't use drawable resources for that. Because Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
If you still want to use your method try
getResources().getIdentifier("bangle1.png", "drawable", getPackageName());
Thanks to all , even i tried it all suggested answers by others , it didnt resolve but i found finally the solution here: How do I get the resource id of an image if I know its name?.
it worked magically:
String mDrawableName = "bangle1";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
Here , myDrawableName should not have extension like : ".png". Thanks to all.
Your problem is that you're writing the image name with its suffix. Try using this code:
int imageResource = getResources().getIdentifier(
"your image name without suffix(bangle1)", "drawable", YourActivtyName.this);

How to load a Google maps static map using Picasso?

In my Android app I use Picasso to load images. This normally works perfectly well.
Today I tried loading a static image from the google maps api, but this doesn't seem to work. When I open the example link as provided on their info page, I get to see the static map image perfectly well. When I load it in my Android app using the line below, I get nothing at all.
Picasso.with(getContext()).load("http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=370x250&maptype=roadmap%20&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318%20&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false").into(mapView);
I also tried to download the image and uploading it to my personal webspace, from which it loads perfectly well, but somehow, it doesn't seem to load directly from the direct google API url.
Does anybody know why this is so, and how I can solve it?
The only programmatic point-of-failure that comes to mind is in parsing the URI. Looking at the current Picasso code (https://github.com/square/picasso/blob/master/picasso/src/main/java/com/squareup/picasso/Picasso.java) I see the following:
public RequestCreator load(String path) {
if (path == null) {
return new RequestCreator(this, null, 0);
}
if (path.trim().length() == 0) {
throw new IllegalArgumentException("Path must not be empty.");
}
return load(Uri.parse(path));
}
So I'd first debug
Uri.parse("http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=370x250&maptype=roadmap%20&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318%20&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false")
and see what that Object looks like. Does it drop or confuse any of your parameters?
If that doesn't lead you anwhere, try downloading the file manually using a HttpClient [or similar]. Then at least you can fully debug the request/response.
Also, I know Google maps has some limits -- are you sure you haven't reached them?
replace http with https
replace | with %7C
add api key
The .loadMap() function has many declared variables. This is the heart of the whole process.
So what is required for the static maps API to give us an image is that we make an http request with a given url, for which an image response (URL) is received. Let us run through the meaning and utility of these variables. Yes, all of them have a completely different meaning!
The mapUrlInitial variable is always the same while making an API call. It has a query of center ( ?center ) which specifies that we want the location to be centered in the map.
The mapUrlProperties variable contains a string where you control the actual zooming of the image response you will get, the size ofthe image and the color of the marker which will point out our place.
The mapUrlMapType variable is a string where you can actually determine the marker size you want and the type of the map. We are using a roadtype map in the app.
Finally latLong is a string which concatenates the latitude and the longitude of the place we want to pinpoint!
We then concatenate all of these strings to form a feasible Url. The Url is then loaded as we have seen above, in the Picasso code. One thing we can notice is that an event object is always required for all of this to happen, because we are able to fetch the position details using the event object! Final Code:-
fun loadMap(event: Event): String{
//location handling
val mapUrlInitial = “https://maps.googleapis.com/maps/api/staticmap?center=”
val mapUrlProperties = “&zoom=12&size=1200×390&markers=color:red%7C”
val mapUrlMapType = “&markers=size:mid&maptype=roadmap”
val latLong: String = “” +event.latitude + “,” + event.longitude
return mapUrlInitial + latLong + mapUrlProperties + latLong + mapUrlMapType
}
//load image
Picasso.get()
.load(loadMap(event))
.placeholder(R.drawable.ic_map_black_24dp)
.into(rootView.image_map)

How to access different 'global' elements without array? (Java)

I'm currently doing Android development.
The class R (an automatically-generated class) has lots of 'global' values accessed from anywhere like so:
R.drawable.<file_name_ignoring_suffix>
I have lots of files named 'item_0.png', 'item_1.png', 'item_2.png' etc.
Is there an easy way to iterate through these items without putting them into an array first?
My current implementation:
int[] itemResources = { R.drawable.item_0, R.drawable.item_1, R.drawable.item_2,
R.drawable.item_3, R.drawable.item_4, R.drawable.item_5 };
... then iterating through the array.
This works well, but it isn't particularly maintainable, and gets laborious when I have many items.
Any ideas?
You could certainly use reflection to get the list of fields of R.drawable. It's kind of hacky, but it might work for you.
I think, there is no easy way to do it. Here is small code i tried to get the drawables.
R.drawable d = new R.drawable();
try {
for (Field fld : declaredFields) {
Integer id = fld.getInt(d);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), id);
if (bitmap != null)
Log.d("tag", "success");
else
Log.d("tag", "failed");
}
} catch (Exception e) {
Log.d("tag", "" + e);
}
In the above test, some of them failed. I dont know the reason as it need further investigation. But this will get you started.
Secondly, also look for this api from theme, if you want to pick the right png using the rules that android platform uses for find the suitable resource based on the orientation, locale etc.
How about putting them in a same directory, then automatically querying the directory content and have it create an array using the contents?

Android: IF statement not working when set by preferences

I am having trouble using and IF statement based on a string from my preferences.
Here is the code:
preferences = PreferenceManager.getDefaultSharedPreferences(this);
String themePref = preferences.getString("theme", "null");
Log.i("Theme", "Current theme is " + themePref );
if (themePref == "dark"){
setTheme(android.R.style.Theme_Black);
}else{
setTheme(android.R.style.Theme_Light);
}
I have two options at this point; light and dark. The code successfully sets themePref as light or dark as needed, and I've confirmed via debugging, but for some reason the if statement fails. I have manually set a string to "dark" and it then works correctly.
Am I missing something here? Why would a string coming from the preferences process any differently?
Any help would be greatly appreciated.
Thanks,
Josh
You should use themePref.equals("dark") (or even better "dark".equals(themePref)) to compare strings. == tells you if the string instances are the same, but two instances can have the same value and not be the same instance.
Is PreferenceManager.getDefaultSharedPreferences(this).getString(...) returning a java.lang.String instance or a subclass? I would replace themePref == "dark" with themePref.equals("dark") instead.

Categories