Converting an edittext value to an array of integers - android

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;
}

Related

How to pass edit text values to integer array in Android

I'm a beginner in Android.
I have created a edit text field where can I enter values from 0-9. Now, I have to get these values in an integer array.
example : entered values are 12345.
I need an array containing these values
int[] array = {1,2,3,4,5};
I need to know the way to do this. Kindly help.
Try this :
String str = edittext.getText.toString();
int length = str.length();
int[] arr = new int[length];
for(int i=0;i<length;i++) {
arr[i] = Character.getNumericValue(str.charAt(i));
}
You can use something like this:
int[] array = new int[yourString.length()];
for (int i = 0; i < yourString.length(); i++){
array[i] = Character.getNumericValue(yourString.charAt(i));
}

Edit text of several buttons using a for loop

I have 16 buttons, whose names are "button1", "button2", and so on. Is there a way I can iterate through them using a for loop, by somehow appending the number value upon each iteration? Something like this:
for(int i = 1; i<17; i++ ){
Button b = (Button)findViewById(R.id.buttoni);
I know I can simply initialize each button in my onCreate() method, but I was just curious if I could do it in a way similar to my example code.
Thank you.
You can use getIdentifier :
for(int i = 1; i<17; i++ ){
int buttonId = getResources().getIdentifier("button"+i, "id", getPackageName());
Button b = (Button)findViewById(buttonId);
//Your stuff with the button
}
You can create an array of Button's and use getIdentifier method that allows you to get an identifier by its name.
final int number = 17;
final Button[] buttons = new Button[number];
final Resources resources = getResources();
for (int i = 0; i < number; i++) {
final String name = "btn" + (i + 1);
final int id = resources.getIdentifier(name, "id", getPackageName());
buttons[i] = (Button) findViewById(id);
}
In case someone is interested how to achive the same result using Java only
The solution above uses Android specific methods (such as getResources, getIdentifier) and can not be used in usual Java, but we can use a reflection and write a method that works like a getIdentifier:
public static int getIdByName(final String name) {
try {
final Field field = R.id.class.getDeclaredField(name);
field.setAccessible(true);
return field.getInt(null);
} catch (Exception ignore) {
return -1;
}
}
And then:
final Button[] buttons = new Button[17];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = (Button) findViewById(getIdByName("btn" + (i + 1)));
}
NOTE:
Instead of optimizing this kind of code you should rethink your layout. If you have 17 buttons on the screen, a ListView is probably the better solution. You can access the items via index and handle onClick events just like with the buttons.

random genaration of image from drawable folder in android

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

get drawable from ImageView

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.

Getting random image from drawable directory with certain name suffix

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.

Categories

Resources