Programatically setting a random image to an ImageButton - java

I'm trying to have the picture used by my ImageButton to be selected randomly.
I think this code should work but there seems to be a problem when passing the resource as a String.
ImageButton getClickTime = (ImageButton) findViewById(R.id.clicker);
Random generator = new Random();
int generatedRandom = generator.nextInt(10) + 1;
String randomImage = "R.drawable.bg" + (String.valueOf(generatedRandom)) ;
Drawable replaceImage = getResources().getDrawable((int) randomImage);
getClickTime.setImageDrawable((Drawable) replaceImage);
I seem to be getting in a bit of a mess with casts of ints, Strings, drawables and CharSequences.
If I manually type in a randomly selected image resource, it works. But if I pass the String to a text-box I can see that it's written exactly the same as when I type it in manually.
Can anyone see what I'm doing wrong here?
Thanks in advance

Your problem is that you are misunderstanding how Android uses resource ids. The R file holds int ids that map to resources contained in your app. You are trying to reference a drawable resource by casting its String reference into an int. That is impossible and doesn't make sense.
What I would suggest is that you create an int[] that holds the ids of all of your drawables that you want to be randomly selected.
int[] imageIds = {
R.drawable.bg1,
R.drawable.bg2,
R.drawable.bg3,
R.drawable.bg4,
R.drawable.bg5
// etc for as many images you have
};
Then, randomly select one of those drawable ids and set that your to ImageButton.
ImageButton getClickTime = (ImageButton) findViewById(R.id.clicker);
Random generator = new Random();
int randomImageId = imageIds[generator.nextInt(imageIds.length)];
getClickTime.setImageResource(randomImageId);

If you want to get the id of a resource you should use something like this:
int id = context.getResources().getIdentifier("resource_name", "drawable", context.getPackageName());
Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), id);

You may want to use an array of all images and get it by random index:
int[] all = {
R.drawable.bg1,
R.drawable.bg2,
};

Related

How to set ImageView Resource from Java Image data type in Android

I am trying to set a Image View resource from a Image Data Type
Something like
//this line is not working
Image storeImage = new Image(R.drawable.butterfly);
ImageView mainImage = findViewById(R.id.mainImage);
//this line is not working either
mainImage.setImageResource(storeImage);
For my work
I need to store image in a variable
then use it later for Image view
Set the drawable directly, to the view:
//store the id of the drawable
int image = R.drawable.butterfly
ImageView mainImage = findViewById(R.id.mainImage);
mainImage.setImageResource(image);
In general, your image is stored, once you added it to your Drawable resource folder.
You can access it with an ID which can be stored in a variable (datatype int):
int storeImage = R.drawable.butterfly;
Then you have to make your ImageView accessible as you already did:
ImageView mainImage = findViewById(R.id.mainImage);
Your code mainImage.setImageResource(storeImage); doesn't work because "storeImage" is an int, but the function expects a Drawable. Each time you want to convert the ID into a Drawable, you have to use getDrawable(storeImage);.
Therefore your whole code would look like this:
int storeImage = R.drawable.butterfly;
ImageView mainImage = findViewById(R.id.mainImage);
mainImage.setImageDrawable(getDrawable(storeImage));
mainImage.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.butterfly));

How to use FaceDetector.class to return the number of faces in a photo

I need to implement some lines of code that, given a bitmap Image, returns to me an int that represents the number of faces in the image. How can I do it using this Class: FaceDetector.Class ?
For now I did it in a really symple way:
Bitmap bmp = image.copy(Bitmap.Config.RGB_565, true);
FaceDetector faceDetector = new FaceDetector(image.getWidth(),image.getHeight(),5);
//int numberFaces = faceDetector.findFaces(image,"Face[faces]");??
I am not understanding what to insert in *Face[faces]*and precisely I am confused about what .findFaces() does (it's the unique method of this Class).
I am sorry if I am not more accurate, but I am not understanding completely this class maybe.
Check the documentation. To quote:
Face: an array in which to place all found FaceDetector.Faces. The
array must be sized equal to the maxFaces value set at initialization
So just pass an empty array of size maxFaces. In your example:
Bitmap bmp = image.copy(Bitmap.Config.RGB_565, true);
int maxFaces = 5;
FaceDetector faceDetector = new FaceDetector(image.getWidth(),image.getHeight(),maxFaces);
Face[] faces = new Face[maxFaces];
int numberFaces = faceDetector.findFaces(image,faces);
//findFaces should've filled the faces array if it detected any, and you can use it.

Using a variable to define a resource

I want to display 5 random dice, of the 6 sided variety. I have code that generates 5 random integers between 1 and 6, and I have 5 ImageViews of dice. They have ids set to: d6_image_view_1, d6_image_view_2, etc. In the drawable folder, I have d1.jpg, d2.jpg, etc. So if I want to change the second picture to a 4, I would do this:
ImageView d6ImageView2 = (ImageView) findViewById(R.id.d6_image_view_2);
d6ImageView2.setImageResource(R.drawable.d4);
What if I have the numbers for the ImageView and drawable in variables? Do I have to do a long, complicated nested if setup to get the right output? Or can I somehow put those numbers right into the code? Obviously this doesn't work:
int image = 2;
int picture = 4;
ImageView d6ImageView(image) = (ImageView) findViewById(R.id.d6_image_view_(image));
d6ImageView(image).setImageResource(R.drawable.d(picture));
There are no dynamic variables in Java. Java variables have to be declared in the source code. So a solution could be to make two arrays of integers for both drawable resources and view id's
For example
int[] resourceIds = new int[] { R.drawable.d1, R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 }
int[] viewIds = new int[] { R.id.d6_image_view_1, R.id.d6_image_view_2, R.id.d6_image_view_3, R.id.d6_image_view_4, R.id.d6_image_view_5, R.id.d6_image_view_6 }
Then you could do
int image = 2;
int picture = 4;
ImageView imgView = (ImageView) findViewById(viewIds[image]);
imgView.setImageResource(resourceIds[picture]);

Folder of bitmaps to int array of drawables for display in RecyclerView

I have a RecyclerView in which I am displaying an integer array of Drawable. However I have a folder of Bitmaps on the sd card I want to display instead. But I have not been able to work out how to convert the bitmaps into drawables and put them into an int array for display or even if this is the best way of working this out.
This is this is the code for where I set my adapter in onCreateView where I use getData() to give the images for the adapter:
adapter = new ProgressImagesListAdapter(getActivity(), getData());
mProgressImagesListRecycler.setAdapter(adapter);
This is getData():
public List<ProgressImagesListInformation> getData() {
List<ProgressImagesListInformation> mFrontViewImagesList = new ArrayList<>();
int[] mImages = new int[]{
R.drawable.boomer,
R.drawable.bosco,
R.drawable.brewster,
R.drawable.dory,
R.drawable.gabby,
R.drawable.hunter,
R.drawable.kitkat,
R.drawable.doug,
R.drawable.mae,
R.drawable.millie
};
for (int i = 0; i < mImages.length; i++)
{
ProgressImagesListInformation current = new ProgressImagesListInformation();
current.mImageId = mImages[i];
mFrontViewImagesList.add(current);
}
return mFrontViewImagesList;
}
The way I was thinking was to change the contents of getdata(), make a for loop that converts the contents of sd card folder bitmaps into array of drawables using somthing like the line below in the for loop but I have not been able to work a way to implement it. This obviously gives me the error found type bitmap expected type integer but I don't understand why or how to fix it.
ArrayList<Integer> ImagesArray = new ArrayList<>();
for (int i = 0; i < sNumberOfFilesInImageDirectory; i++)
{
ImagesArray.add(new BitmapDrawable(getResources(), MyBitmapImage));
}
Thanks for your help.
You'll have to know the location of those images on the SD card. Are they always on the same folder? If so, it'll be easier for you.
First of all, don't forget to declare android.permission.READ_EXTERNAL_STORAGEon your AndroidManifest.xml file.
Then, you'll need to use BitmapFactory along with the path to your images to get the Bitmap objects and put them into a List like an ArrayList or simply use an array.
After that you can use the images like any other. But they won't be int resources, they'll be actual Bitmap objects. To use the resources like R.drawable.someimage they'll have to be located under your res/ folder.
Example:
BitmapFactory.Options opt= new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, opt);
list.add(bitmap); // Or do something else with the Bitmaps.
And if you want to save those images elsewhere, check this answer.
The other steps would require you to understand how to use CardView and RecyclerView. You can read this post on Android Essence and this one on Big Nerd Ranch, and of course this one from the android training guide to get going.
**EDIT: ** And to use a Bitmap on an ImageView, use this:
Bitmap yourBitmap; // Getting from somewhere else.
ImageView myImage = (ImageView) findViewById(R.id.myimageview);
myImage.setImageBitmap(yourBitmap);
And if for some reason you have a Drawable object instead of a Bitmap you can call:
Drawable yourDrawable; // Getting from somewhere else.
ImageView myImage = (ImageView) findViewById(R.id.myimageview);
myImage.setImageDrawable(yourDrawable);
More info on ImageView on this link.

Android: How do I compare ImageSpan drawable to XML resource drawable?

I have a question which I cannot find an answer for too long and I would appreciate if you can help.
I have a TextEdit which I add icons (Emojis) into it between the text.
The Icons are stored in an ImageSpan[] array named imagesInTxt.
Then I loop through the ImageSpan[] and I am trying to compare its drawable or whatever constant value that it can offer to the resource from the XML, Eg: R.Drawable.Smiley that was used as icons in the first place.
The problem is that the unique identifier that returns from getResources().getDrawable(R.Drawable.smiley) does not match the identifier than I get from imagesInTxt[x].getDrawable(), although we are talking about the same icon exactly.
I don't want and don't see a way to use .SetTag() and .GetTag() because I am dealing with ImageSpan[] from within the EditText and not the button itself, so this solution is not helping me.
I don't want to compare the ImageSpan[] directly to the ImageView button. I need to compare it to the original resource that I used (Eg: R.Drawable.xxxx) in any way possible.
How can I achieve that ?
If it is impossible, what can you suggest as an alternative solution ?
ImageSpan[] imagesInTxt = txt.getSpans(0, txt.length(), ImageSpan.class);
for (int x = 0; x < itemSpans.length; x++) { // Go through the ICONS
Drawable myIcon = getResources().getDrawable(R.Drawable.smiley);
if(imagesInTxt[x].getDrawable().equals(myIcon)) {
Icon = ";-)";
}
myIcon = getResources().getDrawable(R.drawable.sad);
if(imagesInTxt[x].getDrawable().equals(myIcon)) {
Icon = ";-(";
}
}

Categories