I am new to Android and I am trying to change the background of an ImageView in Java. This part is working. The problem is I have a 4 images and I would like to randomly choose one and display the image.
For example I have an array of drawables as such:
String[] images = new String[4];
images[0] = "R.drawable.i1";
images[1] = "R.drawable.i2";
images[2] = "R.drawable.i3";
images[3] = "R.drawable.i4";
I was trying to use this to choose a random one:
int idx = new Random().nextInt(images.length);
String random = (images[idx]);
However, I cannot seem to get the setBackground for the imageview to work with these.
For example, I tried:
images.setBackgroundDrawable( getResources().getDrawable(R.drawable.images[random]) );
I know I am not doing it correctly however that is what I would like to do.
You can try this:
int[] images = new int[4];
images[0] = R.drawable.i1;
images[1] = R.drawable.i2;
images[2] = R.drawable.i3;
images[3] = R.drawable.i4;
int idx = new Random().nextInt(images.length);
int random = (images[idx]);
images.setBackgroundDrawable( getResources().getDrawable(images[random]) );
Your problem seems to be, that you want to call a Method through a String. Thats absolutly nonesense unless you work with java SQL calls or XML...whatever. you need the actual image Object if you call your draw method.
well there is a simple solution :D
Instead of using an String[]. Use a ArrayList<Image>
after that you can call the method list.shuffle().
some pseudo Code:
ArrayList<Image> yourImages = new Arraylist<>();
yourImages[1] = image1
yourImages[2] = image2
...
yourImages.shuffle(); //shuffles your list
print(yourImages[1]);
print(yourImages[2]);
...
the first advatage is that your pictures will be displayed at random.
the second advantage is that there is no duplicate of each displayed picture.
PS: It would also work with an Image[] + the Random class. But how come, choose a String[]. a String is a representation of an Text... not an image.
Related
I am trying to move, say a text or number in setText(Integer.toString()) format randomly on 4 different buttons at each click. I am able to obtain the object form of it, but it is worthless since I can't get that information out of it.
This is my code:
public void clickButton(View view){
List mo = new ArrayList();
mo.add(Button);
mo.add(Button1);
mo.add(Button2);
mo.add(Button3); // these are defined in OnCreate method
Random rko = new Random();
int koo = rko.nextInt(mo.size());
Object a = mo.get(koo);
Log.i("here", String.valueOf(mo.get(koo)));
I get this output in the logs up on each click
android.support.v7.widget.AppCompatButton{71c6fe0 VFED..C.. ...PH... 697,708-928,933 #7f0c0052 app:id/Button2}
android.support.v7.widget.AppCompatButton{71c6fe0 VFED..C.. ...PH... 697,708-928,933 #7f0c0052 app:id/Button3}
android.support.v7.widget.AppCompatButton{71c6fe0 VFED..C.. ...PH... 697,708-928,933 #7f0c0052 app:id/Button}
I am new to this. Please help
Thanks.
hi i believe that u should use tags on your buttons p = new Random().nextInt(21);
button.setTag(Integer.toString(alpha));
//here alpha is the text that you wanted to put on the button,get the text from button by using appropriate code
cbutton.setTag(Integer.toString(" "));
You could try writing AppCompatButton instead of Object and then you should be able to get the text of a button with a.getText(); and change the text of a button with a.setText();.
#Rushikesh You did not restrict the random generated number within the range of 0-4.
The size of array list of button is 4 so the the index must be 0-4 to avoid the IndexOutOfBoundsException
List mo = new ArrayList();
mo.add(Button);
mo.add(Button1);
mo.add(Button2);
mo.add(Button3);
int koo = (int)(Math.random() * (10-(mo.size()+1))); // generated number range will be 0-4
Object a = mo.get(koo);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm trying to load several images into an array. But for some reason, I get a NullPointerExeption when trying to do the actual loading (ImageIO.read()). I can't see whats wrong, probably from fiddeling around with it too much that I got blind for the mistake.
This is the loop that tries to load the images:
for (int i = 0; i <= 1; i++) {
try {
image[i] = ImageIO.read(new File(String.format("TDs/TD%d.png", i)));
bg[i] = ImageIO.read(new File(String.format("BGs/BG%d.png", i)));
} catch (IOException e) {
}
}
I currently have only two images to switch between, but I'll change that soon.
The painting happens using
g2d.drawImage(bg[1], 0, 0, null);
Both variables are initialized by
Image[] image, bg;
And last but not least proof that all images are actually there is found
Thanks for helping a stupid person.
EDIT: Thank you alot for the answers, as initiaizing the array this way works!
I feel like an idiot now since I looked at all other array inits to find that they were initialized exactly the same way as you told me... Sorry for stealing your time!
PS: No need to handle IOExeptions since these are textures for a game - they don't change and you can't / shouldn't change them either. I will add a Messagebox with a message in case someone decides to mess around anyways.
You need to create a new array. You only declare the array like so:
Image[] image;
But to store elements in your array you have to initialize it like so:
Image[] image = new Image[2] // value count
For your example you could try this
int imageCount = 2;
Image[] image = new Image[imageCount];
for (int i = 0; i < imageCount; i++) {
try {
image[i] = ImageIO.read(new File(String.format("TDs/TD%d.png", i)));
bg[i] = ImageIO.read(new File(String.format("BGs/BG%d.png", i)));
} catch (IOException e) {
}
}
Or as an alternative, if you don't know how many values you want to store. You could use an ArrayList. Like so:
ArrayList<Image> images = new ArrayList<>();
//add image
images.add(ImageIO.read(new File(String.format("TDs/TD%d.png", i))));
When you are initializing an array of images, you might want to try to do something like this:
Image[] image = new Image[2]; //or replace 2 by the amount of images you will be loading.
Image[] bg = new Image[2]; //same for this one.
This way the array is initialized properly.
Here is a SimpleArcLoader library I am using as progress bar.
https://github.com/generic-leo/SimpleArcLoader
Here is my code:
int[] colors = {R.color.colorPrimaryDark, R.color.colorPrimary};
ArcConfiguration configuration = new ArcConfiguration(getActivity());
configuration.setColors(colors);
SimpleArcDialog mDialog = new SimpleArcDialog(getActivity());
mDialog.setConfiguration(configuration);
mDialog.show();
This always gives me a gray color. I also tried with other colors but same result.
Here is a screenshot
Is my input is wrong? Or is there any solution?
you must declare your array colors like this :
private int mColors[] = {Color.parseColor("#F90101"),Color.parseColor("#0266C8")};
I want to create 2 ArrayList. One holding 16 colors, the other one holding 139.
I have the list with colors (both RGB as 255,126,32 and Hex as 0xFFFF2552). I want to use the ArrayList to later pick random colors from.
I've tried int[], that doesn't work. I've tried ArrayList<Integer> and ArrayList<Color>. My problem is; I don't understand how to add the colors to the ArrayLists.
Thanks!!
For now, I'm exploring this:
Color cBlue = new Color(0,0,255);
Color cRed = new Color(255,0,0);
ArrayList colors = new ArrayList();
colors.add(cBlue);
colors.add(cRed);
and so on...
I really like int[] colors = = new int[] {4,5}; because it's only one line of code... but how do I get colors in, to later on, pick from?
or.. would it be better to store the colors in a strings.xml file and then fill the ArrayList from there? If so, how should I do that?
Thanks!!
You could try:
int[] colors = new int[] {Color.rgb(1,1,1), Color.rgb(...)};
For example, but I don't think it's a good idea to decide only using "one line" argument.
List<Integer> coloras = Arrays.asList(new Integer[]{Color.rgb(1, 1, 1), Color.rgb(...)});
Will also work.
You can create an arraylist in arrays.xml file:
<resources>
<string-array name="colors">
<item>#ff0000</item>
<item>#00ff00</item>
<item>#0000ff</item>
</string-array>
</resources>
Then use the loop to read them:
String[] colorsTxt = getApplicationContext().getResources().getStringArray(R.array.colors);
List<Integer> colors = new ArrayList<Integer>();
for (int i = 0; i < colorsTxt.length; i++) {
int newColor = Color.parseColor(colorsTxt[i]);
colors.add(newColor);
}
In my opinion keeping colors in the list is the most convinient solution.
To take a color from the list randomly, you do:
int rand = new Random().nextInt(colors.size());
Integer color = colors.get(rand);
I would make a text file or xml file populated with the color info and have a function that reads in each line of the file using a loop, creates a Color object for each line and adds it to the array list and then goes to the next line until there are no lines left.
I would recommend against using a configuration file unless you want to be able to change your colors without code changes. I suspect your colors are constant though, so the file would just add unnecessary complexity to your application.
The code sample in your question assumes java.awt.Color when you would actually use the utility class android.graphics.Color which cannot be instantiated.
Therefore I recommend the following solution as a static variable (and be careful not to modify the contents of the array later):
static final int[] colors16 = {
Color.rgb(255, 0, 0),
Color.rgb(0, 255, 0),
Color.rgb(0, 0, 255)
};
Now add a static instance of Random to use for selecting random colors from the list.
static final Random random = new Random();
And then pick your color!
int colorIndex = random.nextInt(colors16.size());
Color color = colors16.get(colorIndex);
If you feel it's important to protect the contents of your list, you can make it immutable as follows, at the small expense of boxing your color ints into Integer objects.
static final List<Integer> colors = Collections.unmodifiableList(
Arrays.asList(
Integer.valueOf(Color.rgb(255, 0, 0)),
Integer.valueOf(Color.rgb(0, 255, 0)),
Integer.valueOf(Color.rgb(0, 0, 255))
)
);
Technically you can leave out the Integer.valueOf() conversion in the above snippet and Java will autobox the ints.
You can also can use int[] colors = new int[]{color1.getRGB(),color2.getRGB()};
And decode using: Color color = new Color(colors[0]);
What you have looks like it makes sense, but you should specify the type of the ArrayList.
List<Color> colorList = new ArrayList<Color>();
colorList.add(cBlue);
... etc
(The difference between declaring it as a List or an ArrayList is that List is the interface that ArrayList implements. This is a generally pretty good practice, but for your purposes it probably won't make a difference if you declare it as a List or an ArrayList).
If you want to do it in fewer lines of code, you can use an ArrayList initializer block, like this:
List<Color> colorList = new ArrayList<Color> { new Color(...), cBlue };
Or with Arrays.asList, which takes in an array and returns a List.
But in general you should get used to verbosity with Java, don't try to optimize your lines of code so much as the performance of those lines.
(Sidenote: make sure you're using the correct Color class. There's android.graphics.Color and java.awt.Color, and they're totally different, incompatible types. The constructor you're using is from java.awt.Color, and with Android you're probably going to want to use android.graphics.Color).
I'm a beginner. I'm making a kid's math game. All it has to do is add the 2 pictures given. The problem is, I don't know how the JTextField will know that the answer is correct. Here's the picture.
ImageIcon[] images = new ImageIcon[10];
images[0] = new ImageIcon("0.jpg");
images[1] = new ImageIcon("1.jpg");
images[2] = new ImageIcon("2.jpg");
images[3] = new ImageIcon("3.jpg");
images[4] = new ImageIcon("4.jpg");
images[5] = new ImageIcon("5.jpg");
images[6] = new ImageIcon("6.jpg");
images[7] = new ImageIcon("7.jpg");
images[8] = new ImageIcon("8.jpg");
images[9] = new ImageIcon("9.jpg");
ImageIcon[] image = new ImageIcon[10];
image[0] = new ImageIcon("0.jpg");
image[1] = new ImageIcon("1.jpg");
image[2] = new ImageIcon("2.jpg");
image[3] = new ImageIcon("3.jpg");
image[4] = new ImageIcon("4.jpg");
image[5] = new ImageIcon("5.jpg");
image[6] = new ImageIcon("6.jpg");
image[7] = new ImageIcon("7.jpg");
image[8] = new ImageIcon("8.jpg");
image[9] = new ImageIcon("9.jpg");
int image_number = (int) (Math.random() * 10);
int image_number1 = (int) (Math.random() * 10);
Pic1.setIcon(images[image_number]);
Pic2.setIcon(image[image_number1]);
I'm not sure if I understood your question correctly, but you can store the value of a pic in some variable in Image.
It's been some time since I've coded in java, but I remember there are fields to store data.
After which all the JTextField has to do, is get the data associated with the 2 images currently being shown and see if the answer is correct or not.
Another good option, can be to name the images equal to their value i.e. an image named "7.png" is actually a diagram showing 7, that way all you have to do, is figure out what 2 images are being shown, parse their name and check for accuracy with the user input.
Update
Just did some quick research - http://docs.oracle.com/javase/7/docs/api/javax/swing/ImageIcon.html
ImageIcon contains a field description, you can simply set that field when creating instances of it & retrieve the one currently rendered.
ImageIcon[] images = new ImageIcon[10];
images[0] = new ImageIcon("0.jpg");
images[0].setDescription("0");
//Other code
then somewhere at some other place, click of a button or keypress of JTextField, it can be retrieved like :
Integer x=Integer.parseInt(Pic1.getIcon().getDescription());
One thing you might consider doing is creating a wrapper class around the image, which not only maintains a reference to the image, but the value of the image
public class NumberImage {
private Image image;
private int value;
public NumberImage(int value, Image image) {
this.value = value;
this.image = image;
}
public int getValue() {
return value;
}
public Image getImage() {
return image;
}
}
This way, you can calculate the answer by simply adding the two values properties together within your program
The other thing you already have is the two indexes of the images to be displayed, wch is the same numerical value of the image to be displayed...
That is, based on your example, image_number == 7 and image_number1 == 5, therefore, you already have the information you need to calculate the answer ;)