I have various images in the res/drawable directory , i want to get a random image from it that has "module_" suffix, then load that into a drawable object.The image names are not not named consecutively i.e 1 ,2 ,3 etc , they have different names describing what it contains i.e. "apple", "banana" etc
Any ideas?
void populate() {
try {
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 0; i <= 48; i++) // 1//
{
number.add(i + 1);
Log.i("nuber in loop ",number.add(i+1)+"");
}
Collections.shuffle(number);
Random r = new Random();
int Start = r.nextInt(number.size());
if (Start - 9 >= number.size() - 1)
Start -= 9;
Log.i("Start ",Start+"");
for (int i = 0; i <=8; i++)
{
String imgName = "img" + number.get(Start);
Log.i("imagename", imgName);
int id = getResources().getIdentifier(imgName, "drawable",
getPackageName());
Log.i("id", id + "");
ImgBtnArray[i].setImageResource(id);
Start++;
}
}
catch (Exception e) {
}
}
into the above function it will
48 is total no of images into drwable from thatany 9 randm img i'll get and it will check for not to allow duplicate no also
in to the above i've 1 to 49 imgs into sequence 1.png,2.png lyk that that is more easy way.. i think bt u can create string array may be this way u can do
I dont think its possible to a get a random image from the drawable directory, so i just hard coded an array with the images and randomly index into that.
Related
I have raw folder with audio files from a.mp3 to z.mp3.
I would like to play them programatically.
int[ ] myMusic = {R.raw.(edittext.getText(first letter),R.raw.(edittext.getText(2nd letter)
How do I make it loop for all my files?
If I understand correctly...
// Get from a Context, such as Activity
Resources r = getResources();
String pkg = getPackageName();
// Extract and loops over text
String letters = edittext.getText().toString();
int size = letters.length();
int[] myMusic = new int[size];
for (int i = 0; i < size; i++) {
// Get the R.raw.letter values
int resId = r.getIdentifier(letters.charAt(i), "raw", pkg);
myMusic[i] = resId;
}
I think you want to play music on whatever String you have typed into your EditText. Every character represents a file name in raw folder. So, you will have to use every characeter of EditText as a file name.
int size = edittext.getText().toString().length();
int[] myMusic = new int[size ];
for(int i=0 ; i < size ; i++){
int resID=getResources().getIdentifier(edittext.getText().toString().substring(i,i), "raw", getPackageName());
myMusic[i] = resID;
}
I'm circulating some drawable images (fx. I have a few images named image_1, image_2 etc.) as header images in a fragment. The images are loaded randomly as I hardcode the number of images available for me, and generate a random index from 0 to this number.
mHeaderBackgroundImagesCount is a final:
private int getHeaderBackground() {
// Random index between 0 and mHeaderBackgroundImagesCount
Random rand = new Random();
int index = rand.nextInt(mHeaderBackgroundImagesCount) + 1;
return getResources()
.getIdentifier("image_" + index, "drawable", getPackageName());
}
As hard coding anything isn't normally the way to go in correct programming, I therefore like to dynamically find out how many 'image_X' drawables I have and set it to mHeaderBackgroundImagesCount.
I would like to do the same with strings from the strings.xml resource file as I'm also circulating some strings on every page load.
Solution Update
This update is inspired by Lalit Poptani's suggestion below. It includes syntax corrections and optimizations and have been tested to work.
private int countResources(String prefix, String type) {
long id = -1;
int count = -1;
while (id != 0) {
count++;
id = getResources().getIdentifier(prefix + (count + 1),
type, getPackageName());
}
return count;
}
System.out.println("Drawables counted: " + countResources("image_", "drawable"));
System.out.println("Strings counted: " + countResources("strTitle_", "string"));
Note: This method assumes that the resources counted start with index 1 and have no index holes like image_1 image_2 <hole> image_4 etc. because it will terminate on first occasion of id=0 thus resulting a faulty count.
If you are sure that your list of drawables will be in a sequence of image_1, image_2,... and so on then you can apply below logic,
int count = 0;
int RANDOM_COUNT = 10; //which is more than your drawable count
for (int i = 1; i < RANDOM_COUNT; i++){
int id = getResources().getIdentifier("ic_launcher_"+i,
"drawable", getPackageName());
if(id != 0){
count = + count;
}
else{
break;
}
}
Log.e(TAG, "This is your final count of drawable with image_x - "+ count);
You use this logic because of there will be no drawable with any name as image_x then id will be 0 and you can break the loop
I am not sure if it's possible to dynamically get the number of resources or drawables.
A way to circumvent this issue is to use string arrays as resources in strings.xml.
e.g.
<resources>
<string-array name="foo_array">
<item>abc1</item>
<item>abc2</item>
<item>abc3</item>
</string-array>
int count = getResources().getStringArray(R.array.foo_array).length;
Android version:4.2
I am developing an android App. I need to generate images from drawable folder randomly. In my drawable I have 45 images with different names.
My xml code is:
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
I have tried with this code:
ImageView img=(ImageView)findViewById(R.id.imageView1);
Random rand = new Random();
int rndInt = rand.nextInt(52) + 1;
String drawableName = "photo"+ rndInt;
int resID = getResources().getIdentifier(drawableName, "drawable", getPackageName());
img.setImageResource(resID);
But with this code I need to change my image names to photo1, photo2, ... and I don't want to do it.
Any suggestion on how to implement it? Thank you.
One way is to create an array with required image's ids. And take random one from that array. That approach is explained in other answers.
Another way is to create file random_images_array.xml in values folder of your project and fill it like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="apptour">
<item>#drawable/image_1</item>
<item>#drawable/photo_2</item>
<item>#drawable/picture_4</item>
</array>
</resources>
And then you can take random image from that xml array:
final TypedArray imgs = getResources().obtainTypedArray(R.array.random_images_array);
final Random rand = new Random();
final int rndInt = rand.nextInt(imgs.length());
final int resID = imgs.getResourceId(rndInt, 0);
Third method is to take random field from R.drawable class:
final Class drawableClass = R.drawable.class;
final Field[] fields = drawableClass.getFields();
final Random rand = new Random();
int rndInt = rand.nextInt(fields.length);
try {
int resID = fields[rndInt].getInt(drawableClass);
img.setImageResource(resID);
} catch (Exception e) {
e.printStackTrace();
}
How about
long[] res = {R.drawable.image1, R.drawable.image2};
or
int[] res = {R.drawable.image1, R.drawable.image2};
and
int rndInt = rand.nextInt(res .length);
img.setImageDrawable(getResources().getDrawable(res[rndInt]));
Be specific about your question - what do you actually want to do?
if you want to show images in random order than this would be best
int resId[]={R.drawable.p1,R.drawable.p2,R.drawable.p2};
Random rand = new Random();
int index = rand.nextInt((resId.length- 1) - 0 + 1) + 0;
imgView.setImageResource(resId[index]);
If you want the absolute file path of image to rename it, see this article for details.
ImageView img=(ImageView)findViewById(R.id.imageView1);
String[] imageArray = {"Image1", "Image2", etc..};
Random rand = new Random();
int rndInt = rand.nextInt(52) + 1;
int resID = getResources().getIdentifier(imageArray[rand], "drawable", getPackageName());
img.setImageResource(resID);
You have to see this question or answer also:-
Randomize string from resources android
but you have to replace
textview.setText()
to
img.setImageResource(ran.nextInt(trivias.length)]);`
I found that setting an array with all of the drawables and then getting a random index through a random number would work.
public int[] Images = {R.drawable.1, R.drawable.2, R.drawable.3};
And then
ImageView EightBallImage = findViewById(R.id.EightBallImage);
EightBallImage.setImageResource(Images[new Random().nextInt(Images.length)]);
Either inside a click listener or just in the onCreate method
ok so i create an array that has integers. The array displays five number from the min and max. How can i display all five numbers in a textview or edittext ? I tried:
nameofile.setText(al.get(x).toString());
but it only displays one?
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
String myString = TextUtils.join(", ", al);
lottonumbers.setText(myString);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(0);
al.add(1);
al.add(5);
al.add(4);
al.add(3);
java.util.Collections.sort(al);//for sorting Integer values
String listString = "";
for (int s : al)
{
listString += s + " ";
}
nameofile.setText(listString);
You're currently only printing out one element (the one at index x). If you want to print them all in order, you can just join them using TextUtils.join().
Update: After seeing your edit, I think there's a better way to go about what you're trying to do. Instead of trying to pull the values one at a time, and update the list, why not just shuffle them, then use the above method?
Update 2: Okay, I think I finally understand your problem. Just a simple change, then.
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
StringBuilder text = new StringBuilder(); // Create a builder
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
if (i > 0)
text.append(", "); // Add a comma if we're not at the start
text.append(x);
}
lottonumbers.setText(text);
al.get(x).toString() will only get the value at index "x". If you want to display all values, you need to combine all of the values from the array into a single string then use setText on that string.
You are only showing one number of your array in the TextView, you must to concat the numbers to see the others results like:
for(Integer integer : al) {
nameofile.setText(nameofile.getText() + " " + al.get(x).toString());
}
Then i think you can show all number in one String.
I am currently building an app that has 6 images on the main view and it generates random images from my drawable folder (shuffling a deck of cards)
initializing the decks:
public static void initDecks() {
int m = 0;
for (int i = 0; i < suites.length; i += 1) {
for (int j = 0; j < regularCards.length; j += 1) {
regularDeck[m++] = "drawablw/" + suites[i] + regularCards[j]
+ ".jpg";
}
}
m = 0;
for (int i = 0; i < suites.length; i += 1) {
for (int j = 0; j < trickCards.length; j += 1) {
trickDeck[m++] = "drawable/" + suites[i] + trickCards[j]
+ ".jpg";
}
}
Collections.shuffle(Arrays.asList(regularDeck));
Collections.shuffle(Arrays.asList(trickDeck));
}
shuffle the deck:
public static String[] getCards(int size) {
String[] result = new String[size];
for (int i = 0; i < size - 2; i += 1) {
result[i] = regularDeck[i];
}
result[size - 1] = trickDeck[0];
Collections.shuffle(Arrays.asList(result));
return result;
}
in my main activity, I assign the cards to the view and when the user clicks on them, I want to know if the image is a trick card or a regular one.
is there a way to find out if the card that was clicked a trick one or not? something like if(image.getImageDrawable().equals(R.drawable.trick.jpg)?
Store the name/id of the drawable at the point where you set it to the ImageView. So you always have a member variable in your class/activity that holds the current image identifier.
Please look ovet this link
Get the ID of a drawable in ImageView
Basically you can set the id in ImageView tag when ever you set the image in ImageView and get from that where you need....
public static Integer getDrawableId(ImageView obj)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
Field f = ImageView.class.getDeclaredField("mResource");
f.setAccessible(true);
Object out = f.get(obj);
return (Integer)out;
}
I found that the Drawable resource id is stored in mResource field in the ImageView object.
Notice that Drawable in ImageView may not always come from a resource id. It may come from a Drawable object or image Uri. In these cases, the mResource will reset to 0. Therefore, do not rely on this much.