Android: Set a random image using setImageResource - android

I need a help with setting a random image using setImageResource method.
In the drawable folder, I have a jpeg file named photo0.jpg, photo1.jpg...photo99.jpg.
And the following code works:
int p = R.drawable.photo1;
image.setImageResource(p);
The above will display photo1.jpg but I want to show a random image.
I tried the following but it doesn't work.
String a = "R.drawable.photo";
int n = (int) (Math.random()*100)
String b = Integer.toString(n);
String c = a+b;
int p = Integer.parseInt(c);//checkpoint
image.setImageResource(p);
It seems like the string "R.drawable.photoXX" isn't being changed to integer at the checkpoint.
Could someone please teach me a right code?
Thank you in advance.

Strings are pretty much evil when it comes to work like this due to the overhead costs. Since Android already provides you with integer id's I would recommend storing all of them to an int array and then using a random number for the index.
The code would look something like this:
int imageArr[] = new int[NUM_IMAGES];
imageArr[1] = R.drawable.photo;
//(load your array here with the resource ids)
int n = (int)Math.random()*NUM_IMAGES;
image.setImage(imageArr[n]);
Here we have a pretty straight forward implementation and bypass all the creation and destruction that occurs with the string concats.

maybe the error is here
int n = (int) (Math.random()*100)
put % not * Like this
int n = (int) (Math.random()%100)
to get all numbers under 100

Related

Creating resource reference ints programmatically

I am building a quiz app with questions in a string resource, as well as an answer. They are formatted by numbers like so:
<string name="ques1">What color is the sky?</string>
<string name="ques2">What sound does a cow make?</string>
The answers are also strings corresponding to the same number as the questions:
<string name="ans1">Blue</string>
<string name="ans2">Moo</string>
I have created a QA class for holding both a question and the answer, as well as the user's response from an EditText. At the "loading" of my app these classes are created and filled by reading from the strings resource.
I can programmatically enter these no problem, it is a lot of copy pasting but it will get the job done:
QA.setQuestion(getString(R.string.ques1));
QA.setAnswer(getString(R.string.ans1));
quizList.add(QA);
QA.setQuestion(getString(R.string.ques2));
QA.setAnswer(getString(R.string.ans2));
quizList.add(QA);
etc...
The problem is that I want to be able to add questions and answers to the xml at any time without having to add yet another repetition of the above method. What I want to do is essentially this:
String refBase = "R.string."
String ans = "ans";
String ques = "ques";
int numOfQues = 25; //only change when questions are added or removed
for (int i = 0; i < numOfQues; i++)
{
String referenceQ = refBase + ques + i;
String referenceA = refBase + ans + i;
QA.setQuestion(getString(referenceQ));
QA.setAnswer(getString(referenceA));
quizList.add(QA);
}
I cannot cast a string to an int like this obviously, but I am wondering if there is a way to implement a reference "builder", where I don't have to repeat many lines of code just to read another string with the same name but incremented number.
I understand that I can also just create an array.xml with one for questions and one for answers, making sure their position in each array corresponds. This would be easiest I think, but I guess I am wondering if it is possible to create references to string values through the code like my example?
You can use this method to get the question or answer String by its resource name:
String getQAString(boolean isQuestion, int index) {
String prefix = isQuestion? "ques" : "ans";
int resId = getResources().getIdentifier(prefix + index, "string", getPackageName());
return resId != 0? getString(resId) : "";
}
The loop to add questions and answers (assume they start from 1 and end at 25):
int numOfQues = 25;
for (int i = 1; i <= numOfQues; i++) {
String referenceQ = getQAString(true, i);
String referenceA = getQAString(false, i);
QA.setQuestion(referenceQ);
QA.setAnswer(referenceA);
quizList.add(QA);
}

Array of methods

I am trying to randomly call methods to make it use a different animation every time to display a textview. I trie using an array but not sure how to implement it. My array looks like this (obviously I know it shouldn't be strings but not sure what data type or if even possible this way).
String [] mAnimations = {"Hinge","RollIn", "Landing",
"BounceIn", "BounceInDown", "BounceInLeft", "BounceInRight",
"BounceInUp", "FadeIn", "FadeInUp", "FadeInDown", "FadeInLeft",
"FadeInRight","FlipInX", "RotateIn", "RotateInDownLeft", "RotateInDownRight",
"RotateInUpLeft", "RotateInUpRight", "SlideInLeft", "SlideInRight",
"SlideInUp", "SlideInDown", "ZoomIn", "ZoomInDown", "ZoomInLeft",
"ZoomInRight", "ZoomInUp"};
Putting any of the correct animations by themselves it works fine (Note BounceInLeft):
YoYo.with(Techniques.BounceInLeft)
.duration(1000)
.playOn(textView);
But what I am trying to do is randomly pick an animation from the array something like this:
Random rand = new Random();
int n = rand.nextInt(mAnimations.length) + 1;
YoYo.with(Techniques.(mAnimations[n]))
.duration(1000)
.playOn(textView);
Thanks for your help
Nicholas
Best Directly Assign method based on Random numbers.Because (mAnimations[n]) value consider as String.
String [] mAnimations = {"Hinge","RollIn", "Landing",
"BounceIn", "BounceInDown", "BounceInLeft", "BounceInRight",
"BounceInUp", "FadeIn", "FadeInUp", "FadeInDown", "FadeInLeft",
"FadeInRight","FlipInX", "RotateIn", "RotateInDownLeft", "RotateInDownRight",
"RotateInUpLeft", "RotateInUpRight", "SlideInLeft", "SlideInRight",
"SlideInUp", "SlideInDown", "ZoomIn", "ZoomInDown", "ZoomInLeft",
"ZoomInRight", "ZoomInUp"};
Random rand = new Random();
int n = rand.nextInt(mAnimations.length);
if(n==0)
{
YoYo.with(Techniques.Hinge).duration(1000).playOn(textView);
}
if(n==1)
{
YoYo.with(Techniques.RollIn).duration(1000).playOn(textView);
}

Changing activity background by path

I try to change the background of my Activity ( onCreate ) randomly. It stucks in the the last step ... show it. Maybe someone has an idea for me.
I created an array within a xml file which contains 5+ drawable's - it looks like this ..
<array name="backgrounds">
<item>#drawable/bg1_320x480</item>
<item>#drawable/bg2_320x480</item>
<item>#drawable/bg3_320x480</item>
<item>#drawable/bg4_320x480</item>
<item>#drawable/bg5_320x480</item>
<item>#drawable/bg6_320x480</item>
</array>
Within my main activity, I get one random element out of the array ...
String[] mTempArray = getResources().getStringArray(R.array.backgrounds);
int iMin = 0;
int iMax = 5;
int randomIndex = iMin + (int) (Math.random() * iMax);
String resPath = mTempArray[randomIndex];
resPath return me (e.g.) res/drawable-hdpi/bg4_320x480.png. From this point on, I found a lot of solutions, but nothing brings me to succes.
What is the last point to set / change / overwrite the background?
A resource ID is just an integer--there's no need to deal with strings. You can use something like this
int[] imageIds = new int[] { R.drawable.bg1, R.drawable.bg2, ... };
, pick a random element, and set it as your background. Not sure if you can encode the array of resource IDs in xml.

How to refer to a random integer in R.raw method in Android?

I have this code
Random x = new Random(44);
int l = x.nextInt();
int path = R.raw.l;
I know it doesn't work that way,but it explains my situation the most.
i.e. Providing l==5, i want to use R.raw.5 as the path. however, R.raw seems to understand only straightforward values, not the referred ones.
Please help!
You can get int indentifier from your activity with this code:
Random x = new Random(44);
int l = x.nextInt();
int path = getResources().getIdentifier(String.valueOf(l), "raw", getPackageName());
More info in documentation: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29

android dynamical binding

I want to work dynamically therefore I want to bind text views dynamically I think an example would explain me the best
assuming I want to bind 7 image views i can do it like this :
Country = (EditText)findViewById(R.id.CountryEditText);
City = (EditText)findViewById(R.id.CityEditText);
LivinigCreture = (EditText)findViewById(R.id.LivingCretureE);
Nature =(EditText)findViewById(R.id.NatureEditText);
Inanimate = (EditText)findViewById(R.id.InanimateEditText);
KnowenPersonality = (EditText)findViewById(R.id.KnowenPersonalityEditText);
Occupation = (EditText)findViewById(R.id.OccupationEditText);
but lets change 7 with NUMOFFILEDS as a final where i want to do the previous ?
myImages = new ImageView [7];
for (int i = 0; i<7;i++,????)
myImages[i] = (ImageView)findViewById(R.id.initialImageView01);
notice : in my R file the R.id.initialImageView01 - R.id.initialImageView07 are not generate in a cont gap between them therefore I don't know how to make this architecture possible .
and if there's a way can someone show me an example how to work dynmiclly (like using jsp on android combined way or something ?)
id its possiable to do so constant times is it possible to build an the same xml constant num of times like jsp does
thank u pep:)
You can store the IDs themselves in an array at the beginning of your Activity; that way you'll only need to write them once and you can index them afterwards.
Something like:
int[] initialImageViewIds = {
R.id.CountryEditText,
R.id.CityEditText,
R.id.LivingCretureE,
R.id.NatureEditText,
R.id.InanimateEditText,
R.id.KnowenPersonalityEditText,
R.id.OccupationEditText
};
Then you can access them with:
myImages = new ImageView [7];
for (int i = 0; i<7;i++) {
myImages[i] = (ImageView)findViewById(initialImageViewIds[i]);
}
If that's not enough and you really want to get the IDs dynamically, I suppose you can use reflection on the R.id class, possibly with something like R.id.getClass().getFields() and iterate on the fields to check if their names interest you. Check reference for the Class class, too.

Categories

Resources