I'm trying to create an app that will generate random number. I found this generate number coding and it is working perfectly. However I have problem when I want to display the generate number to the layout.
For example, the generator will generate two numbers ; numberOne=3 and numberTwo=1. Then it will display imageview number 3 and imageview number 1 on the layout page. Since I'm new to this so how can I display the imageview of the numbers based on the number being generated. Thanks :)
Generate number coding
Random randomNum=new Random();
int numberOne;
numberOne=1+randomNum.nextInt(10);
System.out.println(numberOne + " ");
This is the example of the display
You just need to load the image into already defined ImageView.
// fetch image resource id
// first parameter is the image name without the extension
int id = getResources().getIdentifier("image_name", "drawable", getPackageName());
// assign it to ImageView
imageView.setImageResource(id);
Related
I am trying to interact with dynamically generated buttons. I want to update text and background color for those player clicked and for those who is near by horizontal or vertical axis at the moment of a click.
What I've tried. I've found an id property of a button in XML which led me to idea that I can make a text key to refer to a programmatically generated button. But when I've tried to assign an id - IDE was expecting a number (Int), not a string. Since buttons form a square array - I decided to encode each button via 4 digit number where first 2 digits stand for a row number and other two stand for a column number. Though when I tried to use findViewById IDE told me that it was expecting a special id data type, not a number.
That's how it looks for now:
for (i in 1..size) {
for (j in 1..size){
val button = Button(this)
button.id = i*100 + j
constraintLayout.addView(button)
}
}
What idea or method could I look at?
If you created it dynamically you can save it in a variable (or an array) for later use.
val myButtons = ArrayList<Button>()
for (i in 1..size) {
for (j in 1..size){
val button = Button(this)
myButtons.add(button)
constraintLayout.addView(button)
}
}
if you have a layout with dynamically created views and you know their order you can get them with getChildAt(index).
Alternatively you can assign ids saved in xml like this.
I am reading data of employees from excel file stored in internal storage, unfortunately the app is totally offline and so have offline images , which i need to store in drawable folder.
Now the question i have is ;
There are 350 images named as employee id , for example
1.jpg of emp id = 1 , 2.jpg of emp id = 2.
I am using RecyclerView , in that onBindViewHolder method i have to set images according to the employee id.
Please guide me to show the image into imageView.
Please comment for more input from my side.
Plz dont mark it negative if you can't answer.
You could try something like this.
Example if trying to get employee 1526 the drawable would be R.drawable.1526
String id = employee.getId(); //1526
int imageId = context.getResources()
.getIdentifier(id, "drawable", context.getPackageName());
id being a string.
then with the image view
imageView.setImageResource(imageId);
I have a little question concerning the usage of
Android Resouce by ID / Change image onClick / no change of imageView
I have established my images picked randomly here, using:
#Override
public void onClick(View v) {
Log.d("MYAPP", "Like-Button clicked");
/*imageViewMeasurement.setImageResource(R.drawable.p13);*/
TypedArray images = getResources().obtainTypedArray(R.array.images_primes);
int chosenImageNumber = (int) (Math.random() * images.length());
// setImageResource to the random chosenImageNumber
imageViewMeasurement.setImageResource(images.getResourceId(chosenImageNumber, R.color.colorPrimaryDark));
images.recycle();
// Confirmation if the random generator picked a Number from the array
String chosenImageNumberTest = String.valueOf(chosenImageNumber);
Log.d("MYAPP Choice Number", chosenImageNumberTest);
}
This runs through an array of 40 images and will be repeated one time. So every image will be shown two times (?).
That's the question:
When I use a pool of 40 images randomly for 80 picks, do I get every image two times (draw with cover), or is every try a new random out of those 40 images (draw without replacement), so the reult could be number 1 for 4 times and number 38 for 0 times? Is there an other function that prevents to such a behaviour?
Best,
tigercode
As I understand your code, you would NOT get every image twice, you would get some images multiple times and some images might not even come at all.
Don't use Random if you don't actually want Random. By the laws of probability you'd only have a chance of getting the same image twice, not a certainty.
You could use a boolean array to keep track of which numbers have already been used (if index n is true this means the number has already been taken e.g.).
Edit: The comment below from vims liu is right. It's much more efficient run time wise to define a list of indexes and shuffle the list.
So better use the following solutions, even if it won't make a big differences considering your numbers are quite small.
List<Integer> indexes = Arrays.asList(1,2,3,4,5,6,7,8,9,10); //...
Collections.shuffle(indexes);
You can then iterate through the indexes list and use the current number as current index.
Sorry for answering late, and sorry for a beginner question, I'm new to android developing.
I changed my code (and write my comment what I understood it does:
#Override
public void onClick(View v)
Log.d("MYAPP", "Like-Button clicked");
// 1. Get the array of images in the images_primes XML-List AS int (number of every image in array)
TypedArray images = getResources().obtainTypedArray(R.array.images_primes);
// 2. Takes an array-list and shuffles it
List<Integer> indexes = Arrays.asList(1,2,3,4,5,6,7,8,9,10); //...
Collections.shuffle(indexes);
// Great, it shuffles! ;-)
Log.d("MYAPP", indexes);
// 3. takes the number from the shuffled image list
int chosenImageNumber = (int) (indexes);
// 2. Old code: picks a number out of the image array from 1. / commented out
//int chosenImageNumber = (int) (Math.random() * images.length());
// 4. setImageResource to the random chosenImageNumber
imageViewMeasurement.setImageResource(images.getResourceId(chosenImageNumber, R.color.colorPrimaryDark));
images.recycle();
// Confirmation if the random generator picked a Number from the array
String chosenImageNumberTest = String.valueOf(chosenImageNumber);
Log.d("MYAPP Choice Number", chosenImageNumberTest);
}
Step 1: Open the list of images (as items), use it as array (1,2,3)
Step 2: Have a second number of arrays (possible to connect 1 and 2), SHUFFLE! :-)
Step 3: Here is my problem. If I got that right, I get a string-list from step 2, which numbers I can't use as Int (Error "Integer to int" won't work) -> result should be a number (?)
Step 4: Number from 3 should be used to pick out an image from list / array from 1.
I think, there is a thinking error on my side.
Thanks for your help in advance,
tigercode
I have 100 images in my application of different cities and I want to divide these pictures in different groups, lets say in evening, morning, sunny, raining etc…
We know that when we call an image from layout folder by calling R.layout.image_1, android generates integer number for each image
For example:
R.layout.image_1 (223344), R.layout.image_2 (556677),
R.layout.image_3 (778899),
I can create one table having evening, morning fields and I can assign group of pictures to each of them with integer IDs which are (223344,556677) and I can call evening or morning group and i can display all images related to these group.
My question is: Does Android generate same number every time. Are these numbers are fixed? When ever the application runs.
If its true then upper idea will work for me. If this idea is incorrect then kindly guide me what is the decent approach to handle hundreds of PNGs in application.
Those numbers are not fixed. R will be regenerated and can have completely different numbers if you change something. That is why when comparing ids, you compare by the name instead.
Eg instead of
if (i == 223344)
do
if (i == R.layout.image_1)
Since R.layout.image_1 references the integer id, the name won't change (unless you change the layout xml name.
If you want to get a resource id dynamically (by a string representing the name), you should have a look at this method - Resources#getIdentifier().
First of all we generally put images in the drawable folder.
Does Android generate same number every time?
No.
Are these numbers fixed whenever the application runs?
Yes.
In fact, once your project is built, the ids will remain the same for that same build.
In other words for a certain generated APK file, the ids won't change.
So how can you take advantage of that to group your resources?
You could have a static int array that holds the ids:
public static final int[] IMAGES_MORNING = {R.drawable.morning0, R.drawable.morning1, etc};
public static final int[] IMAGES_EVENING = {R.drawable.evening0, R.drawable.evening1, etc};
Although a more structured method would be to store them in a database on your app's first launch.
Or you could use what A--C suggests:
For example to get all the ids of morning images
for(int i = 0; i < numberOfMorningImages ; i++){
int id = getResources().getIdentifier("morning" + i, "drawable", getPackageName());
// do something with the id
}
No, there's no guarantee that integers will be the same every time, so the solution you've described won't work. Unfortunately, there's no proper way to group drawables inside the res/drawable folder. As a workaround, you can store them inside the assets folder, where you can group them as you like. However, Android won't be able to handle different resolutions this way. The choice is up to you. Hope this helps.
I have a number of images in my directory.
I want to show random images in ANDROID.
Please anyone provide me with an example.
Assume that your images are named img1.png, img2.png, and so on, and they are located in res/drawable folder.
Then you can use the following code to randomly set an image in an ImageView
ImageView imgView = new ImageView(this);
Random rand = new Random();
int rndInt = rand.nextInt(n) + 1; // n = the number of images, that start at idx 1
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setImageResource(id);
I don't have an example but I can provide you an idea.
Build a list of images in an array
Generate a random number between 0 to 1 less than the number of images in folder
Use the random number in step 2 as an index to the array and pick up the image for display.
You have to combine some things. First you need an ImageView in order to display an image on the Android phone.
Then I would take a look into a random number generator (e.g. http://docs.oracle.com/javase/6/docs/api/java/util/Random.html) so that you can get a random number.
By combining these to things, you can randomly select a picture from a list of available pictures and display it using the ImageView.