i am using 9 image view's i want set images to imageview randomly , when I click on refresh button, but I tried like this it's working for random allocation of images but it's repeating the same image in two (or) three imageview's at a time. where is the problem in my code..
final int[] imageViews = {
R.id.imgview11, R.id.imgview12, R.id.imgview13,
R.id.imgview21, R.id.imgview22, R.id.imgview23,
R.id.imgview31, R.id.imgview32, R.id.imgview33 };
final int[] images = {
R.drawable.i1, R.drawable.i2, R.drawable.i3,
R.drawable.i4, R.drawable.i5, R.drawable.i6,
R.drawable.i7, R.drawable.i8, R.drawable.empty };
final ImageButton shuffle = (ImageButton) findViewById(R.id.new_puzzle);
shuffle.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Random generator = new Random();
//int n = 9;
//n = generator.nextInt(n);
//Random random = new Random(System.currentTimeMillis());
for(int v : imageViews) {
ImageView iv = (ImageView)findViewById(v);
iv.setImageResource(images[generator.nextInt(images.length - 1)]);
}
}
});
i don't want repeat, one image for one imageview only..
using the post of blessenm ,i wrote a similar code that you need. check if this helps you.
shuffle.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Random rng = new Random();
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < 9; i++)
{
while(true)
{
Integer next = rng.nextInt(9) ;
if (!generated.contains(next))
{
generated.add(next);
ImageView iv = (ImageView)findViewById(imageViews[i]);
iv.setImageResource(images[next]);
break;
}
}
}
}
});
Maybe not the perfect answer, but I would just shuffle the images list and the set the resulting image to the imageview.
This will avoid having to generate random numbers that will of course create duplicate (If you throw a dice 6 times, you won't have the numbers 1,2,3,4,5,6 in random order, you will get multiple time the same number.)
Please check everything including the 'i' as I am not in front of my computer.
List<int> list = Arrays.asList(images);
// Here we just simply used the shuffle method of Collections class
// to shuffle out defined array.
Collections.shuffle(list);
int i=0;
// Run the code again and again, then you'll see how simple we do shuffling
for (int picture: list) {
ImageView iv = (ImageView)findViewById(imageViews[i]);
iv.setImageResource(picture);
i++;
}
as an alternative, you may also want to shuffle your list with this code:
public class ShuffleArray {
public static void shuffleArray(int[] a) {
int n = a.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = i + random.nextInt(n - i);
swap(a, i, change);
}
}
private static void swap(int[] a, int i, int change) {
int helper = a[i];
a[i] = a[change];
a[change] = helper;
}
public static void main(String[] args) {
int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7 };
shuffleArray(a);
for (int i : a) {
System.out.println(i);
}
}
}
You might want to refer to this post. It shows a method to generate random numbers without duplicates
Creating random numbers with no duplicates
Related
We are trying to use this array of integers in other methods. Setting the final shuffled Array to a global variable has become next to impossible. We have set other variable as global. The goal here is to have a new int [] fix array every time a button is clicked. We have been able to generate a random int [] ar but can not utilize the array in other methods. So our questions after making the random int [] ar how can we use it in the onClickBtnOne method? Code with comments below
public class MainActivity extends AppCompatActivity {
Button btn1,btn2,btn3,btn4,btn5,btn6;
String T1,T2,T3,T4,T5,T6;
int test[] = new int[7];
int count = 0;
int v1,v2,v3,v4,v5,v6;
int[] fix = {3,2,1,4,6,5};
// Trying to not use above values
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
main(null);
}
// end onCeate
public static void main(String args[]) {
int [] fix = {1,2,3,4,5,6};
shuffleArray(fix);
// Want to USE this fix shuffleArray
//==================================
for (int i = 0; i < fix.length; i++) {
System.out.print(fix[i] + ",");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int [] ar) {
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
public void onClickBtnOne(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
count = count + 1;
v1 = count;
test[v1] = count;
if(fix[0] == test[v1]){
// Need a global fix[] here
// =========================
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}
The array you are trying to use does not have an add method you need to put the values in from another variable like this ar[i] = a; So if you use this type of Array declaration List value = new ArrayList<>(); where you declared the other global variable life will be much easier. Modified code below
This will do the shuffle NOTICE value.clear() without this the List will grow each time it is initialized
public void shf(View view){
value.clear();
for (int i = 1; i <= 6; i++) {
value.add(i);
}
Collections.shuffle(value);
}
And here is your test method call value.get(index) Arrays are ZERO based
public void on1(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
if(value.get(0) == 1){
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}
I am trying to set an image based on the enum. I did try to do some research on how to do that using this post : How to match int to enum
but wasn't really sure how to actually use it according to my code.
Here's the enum:
public enum ImageValue{
Image1(1,R.drawable.clubs1),
Image2(2,R.drawable.hearts),
Image3(3,R.drawable.diamonds),
Image4(4,R.drawable.spades);
private int imagevalue;
private int image;
private ImageValue(int value, int drawable){
this.imagevalue = value;
this.image = drawable;
}
public int getImageValue(){
return image;
}
}
This is where I am getting the image values and other values:
public void NewDeck() {
deck = new ArrayList<Card>();
for (int i = 0; i < 13; i++) {
value = CardValue.values()[i];
for (int j = 0; j < 4; j++) {
card = new Card(value, Suit.values()[j], ImageValue.values()[j] );
this.deck.add(card);
}
}
Collections.shuffle(deck);
Iterator<Card> cardIterator = deck.iterator();
System.out.println(deck.size());
while (cardIterator.hasNext()) {
aCard = cardIterator.next();
}
System.out.println("One Card Value" + "--" + aCard.getCardValue()
+ " of " + aCard.getSuit()+"--"+"Image Value" +"----" + aCard.getImagevalue());
}
Here's one solution from the post I mentioned:
**coinView.setImageResource(coinArray[x].getImage());**
Now, On click of a button I want to set that random image that's being generated to one of my image views.
Here:
public void onClick(View v) {
randomImage.setImageResource(**Want to put the image here!**);
}
I am a bit new to Enum concept and not sure how exactly to use it.
A little help will be really appreciated..Thank's in advance.
i wanted to make an application in which i have to randomaly generate images but in order....
like :- APPLE.... i want to generate it as A_PP_E....
but i also want them uniqualy every time
final int[] imageViews = {
R.id.imageView2, R.id.imageView10, R.id.imageView3,
R.id.imageView4, R.id.imageView5, R.id.imageView6, R.id.imageView8 };
int[] photos={R.drawable.aa, R.drawable.pp
,R.drawable.ee,
R.drawable.pp_blue,R.drawable.ll};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for randomizing the view
Random rng = new Random();
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < 5; i++)
{
while(true)
{
Integer next = rng.nextInt(5) ;
if (!generated.contains(next))
{
generated.add(next);
ImageView iv = (ImageView)findViewById(imageViews[i]);
iv.setImageResource(photos[next]);
break;
}
}
}
Step 1): put the images in the array in correct order as follows:
int[] photos={R.drawable.aa, R.drawable.pp, R.drawable.pp_blue, R.drawable.ll, R.drawable.ee}; // correct order APPLE
Step 2): Update your code as below:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rng = new Random();
List<Integer> generated = new ArrayList<Integer>();
// select `n` places which will be "BLANK"
int n = 2; // example `n=2`
for (int i = 0; i < n; i++)
{
while(true)
{
Integer next = rng.nextInt(5) ;
if (!generated.contains(next))
{
generated.add(next);
break;
}
}
}
// now `generated` has `n` random positions
// set these `n` positions as "BLANK" rest as "FILLED"
for (int i = 0; i < 5; i++)
{
ImageView iv = (ImageView)findViewById(imageViews[i]);
if(generated.contains(i)) {
// this was a random selected position
// set it blank or empty
iv.setImageBitmap(null);
}
else {
// set this image as the correct alphabet
iv.setImageResource(photos[i]);
}
}
}
i m doing this for getting blank images in another image view array....and its giving correct output
int n = 2; // example `n=2`
for (int i = 0; i < n; i++)
{
while(true)
{
Integer next = rng.nextInt(5) ;
Log.i("test","value:-"+next);
if (!generated.contains(next))
{
generated.add(next);
break;
}
}
}
for (int i1 = 0; i1 < 2; i1++)
{
ImageView ne = (ImageView)findViewById(nextimages[i1]);
ne.setImageResource(photos[generated.get(i1)]);Log.i("test","value:-"+photos[generated.get(i1)]);
}
Hi can some one suggest me a sample example of how i can sort the textviews based on the numbers in textviews. I am able to get the text from the TextViews need to sort and place the lowest number first.
Thank you.
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
//here I want to assign sorted numberes to the TextViews
}
}
So I have followed Jeffrey's advice. Here is the code which still doesn't work properly. What could be wrong?
Created an array of TextViews:
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
tvs[2] = textView43;
tvs[3] = textView53;
tvs[4] = textView63;
tvs[5] = textView73;
tvs[6] = textView83;
Sorted the array and assinged new values to the TextViews:
Arrays.sort(tvs, new TVTextComparator());
textView23.setText(tvs[0].getText().toString());
textView33.setText(tvs[1].getText().toString());
textView43.setText(tvs[2].getText().toString());
textView53.setText(tvs[3].getText().toString());
textView63.setText(tvs[4].getText().toString());
textView73.setText(tvs[5].getText().toString());
textView83.setText(tvs[6].getText().toString());
And here is the Comporator class:
public class TVTextComparator implements Comparator<TextView> {
public int compare(TextView lhs, TextView rhs) {
Integer oneInt = Integer.parseInt(lhs.getText().toString());
Integer twoInt = Integer.parseInt(rhs.getText().toString());
return oneInt.compareTo(twoInt);
}
}
to sort your textViews, first put them in an array,
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
// and so on
note that if you have handle to the parent container, you could easily build the array by using ViewGroup.getChildCount() and getChildAt().
now write a comparator for a text view,
class TVTextComparator implements Comparator<TextView> {
#Override
public int compare(TextView lhs, TextView rhs) {
return lhs.getText().toString().compareTo(rhs.getText().toString());
// should check for nulls here, this is NOT a robust impl of compare()
}
}
now use the comparator to sort the array,
Arrays.sort(tvs, 0, tvs.length, new TVTextComparator());
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
textView23.setText(intValues[0]);
textView33.setText(intValues[1]);
textView43.setText(intValues[2]);
textView53.setText(intValues[3]);
textView63.setText(intValues[4]);
textView73.setText(intValues[5]);
textView83.setText(intValues[6]);
}
Here is my class it goes in to infinite loop please check where I am going wrong ... I am trying to get id's of image view making it random and then trying to set text view with imageview's description
public class Object {
int ObectIds[];
LinearLayout HUDDisplay;
int HudDisplayText[] = {R.id.HUD_Text_Element1,
R.id.HUD_Text_Element2,
R.id.HUD_Text_Element3,
R.id.HUD_Text_Element4,
R.id.HUD_Text_Element5,
R.id.HUD_Text_Element6,
R.id.HUD_Text_Element7};
TextView[] text;
View v;
Object(Context context,View vs) {
super();
ObectIds = new int[8];
HUDDisplay=(LinearLayout)vs.findViewById(R.id.HUD_Display);
for (int i = 0; i < 8; i++) {
ObectIds[i] = (R.id.imageView1) + i;
Log.d("ImageView", "Image Id's " + ObectIds[i]);
}
randomize(vs);
setTextView();
}
public void setTextView()
{
for(int i=0;i<8;++i)
{
text[i] =(TextView) HUDDisplay.findViewById(HudDisplayText[i]);
text[i].setText(v.getContentDescription());
}
}
public void randomize(View vs) {
for (int i = 0; i < 8; i++) {
while (true) {
shuffleArray(ObectIds);
v = vs.findViewById(ObectIds[i]);
Log.d("Image", "Image Id's " + v.getId());
if (!v.isClickable()) {
v.setClickable(true);
break;
}
}
}
}
static void shuffleArray(int[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i >= 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
Hey man I observed your code & found error in code :
Please compare following code with your code... Constructor
for (int i = 0; i < 8; i++) {
ObectIds[i] = **HudDisplayText[i]**;
Log.d("ImageView", "Image Id's " + ObectIds[i]);
}
You have a while(true) loop that you break from only if v is not clickable. What happens if v is clickable? Nothing in your code ever sets v to not clickable, and views by default are not clickable.
I notice you're using the Object class. Object is basically the root of which all classes extend. If you call super() in the constructor, it will call the super class constructor, which is Object as well... That might be the problem.
Try looking for tutorials on how to start with Java/Android, since you are also using variables names that are not recommended. E.g. in Java,:
- a Class starts with a Capital
- a variable, starts with lowercase
- a function starts with lowercase:
public class Captial
{
private int anIntegerStartsWithLowerCase;
private void functionsAreLowerCaseAsWell()
{
}
}
Also take a look at your loop... It looks like it is never ending