what I will use to prevent the image from appearing again. I want the image won't reapeat appearing but don't know what can I use to do that.
public ImageView imgViewQuestion;
int [] image_list = {
R.drawable.forms,
R.drawable.tags,
R.drawable.tables,
R.drawable.radiobutton,
R.drawable.checkbox,
R.drawable.font,
R.drawable.anchors,
R.drawable.html
};
private void setupList() {
Random random = new Random();
int imageSelected = image_list[random.nextInt(image_list.length)];
imgViewQuestion.setImageResource(imageSelected);
fourinfoassucommon.imageSelected = imageSelected;
correct_answer = getResources().getResourceName(imageSelected);
correct_answer = correct_answer.substring(correct_answer.lastIndexOf("/") + 1);
answer = correct_answer.toCharArray();
fourinfoassucommon.user_submit_answer = new char[answer.length];
suggestSource.clear();
for (char item : answer) {
suggestSource.add(String.valueOf(item));
I have three array
int[] image = {R.drawable.img1,R.drawable.img2} int[] sound= {R.raw.m1,R.raw.m2} String[] nom ={"el1","el2"}
I tryed to change a view with imageview, text from those array when click button but i got only the last value from three array these my method i call when onclick method
private void updateData() {
while (i<nom.length) {
ImageView.setImageResource(image[i]);
textview.setText(nom[i]);
mysong = MediaPlayer.create(Activity.this, sound[i]);
mysong.start();
i++;
}
}
Try this....
Random random = new Random();
private void updateData() {
int random_number = random.nextInt(image.length);
ImageView.setImageResource(image[random_number]);
textview.setText(nom[random_number]);
mysong = MediaPlayer.create(Activity.this, sound[random_number]);
mysong.start();
}
Note : Make Sure Your All Three Array Same Size...
Try this....
int anInt = 0;
And After OnClick
private void updateData() {
if (anInt < image.length - 1) {
anInt++;
} else {
anInt = 0;
}
ImageView.setImageResource(image[anInt]);
textview.setText(nom[anInt]);
mysong = MediaPlayer.create(Activity.this, sound[anInt]);
mysong.start();
}
Note : Make Sure Your All Three Array Same Size...
Alright so here is my problem and my question to you.....
I have a game in which it needs to load images from the jar file (all the images are packed into the jar file like so):
I first have the unzip of the jar file:
Then it goes to:
Then inside each of those folder i have something that looks like this:
Now reminder above is the Jarfile GameClient.jar unziped and you see where the cards are in it.
So here is my code for trying to load each and every one of those images into memory
private void addCardsAndChangeSize() throws IOException
{
String tempString;
ImageIcon tempIcon;
allCards.clear();
ClassLoader cldr = this.getClass().getClassLoader();
URL imageURL;
for(int i = 0; i < all.length; i++)
{
for(int x = 0; x < clubs.length; x++)
{
tempString = all[i][x];
tempString = "/cards/"+cardFolders[i]+"/"+tempString;
imageURL = cldr.getResource(tempString);
tempIcon = resizeImage(new ImageIcon(imageURL),70,70,false);
tempString = all[i][x];
tempIcon.setDescription(tempString);
allCards.add(tempIcon);
}
}
backCard = resizeImage(new ImageIcon(cldr.getResource(back)),70,70,false);
}
So i call that in the contructor to load all the images into an ArrayList here is the whole class if you want to know what i do.
package global;
import java.awt.*;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Cards
{
private ImageIcon backCard = new ImageIcon("cards/backCard.jpg");
private String back = "/cards/backCard.jpg";
private String[] cardFolders = {
"clubs","diamonds","hearts","spades"
};
private String[] clubs = {
"aceClubs.jpg","eightClubs.jpg","fiveClubs.jpg","fourClubs.jpg","jackClubs.jpg",
"kingClubs.jpg","nineClubs.jpg","queenClubs.jpg","sevenClubs.jpg","sixClubs.jpg",
"tenClubs.jpg","threeClubs.jpg","twoClubs.jpg"
};
private String[] diamonds = {
"aceDia.jpg","eightDia.jpg","fiveDia.jpg","fourDia.jpg","jackDia.jpg","kingDia.jpg",
"nineDia.jpg","queenDia.jpg","sevenDia.jpg","sixDia.jpg","tenDia.jpg","threeDia.jpg",
"twoDia.jpg"
};
private String[] hearts = {
"aceHearts.jpg","eightHearts.jpg","fiveHearts.jpg","fourHearts.jpg","jackHearts.jpg",
"kingHearts.jpg","nineHearts.jpg","queenHearts.jpg","sevenHearts.jpg","sixHearts.jpg",
"tenHearts.jpg","threeHearts.jpg","twoHearts.jpg"
};
private String[] spades = {
"aceSpades.jpg","eightSpades.jpg","fiveSpades.jpg","fourSpades.jpg","jackSpades.jpg",
"kingSpades.jpg","nineSpades.jpg","queenSpades.jpg","sevenSpades.jpg","sixSpades.jpg",
"tenSpades.jpg","threeSpades.jpg","twoSpades.jpg"
};
private String[][] all = {
clubs,diamonds,hearts,spades
};
private ArrayList<ImageIcon> allCards = new ArrayList<ImageIcon>();
public Cards()
{
try
{
addCardsAndChangeSize();
shuffle();
}
catch(Exception e)
{e.printStackTrace();}
}
/**
* #param x Cards name with extension
* #return Face Value of Card
*/
public static int getFaceValue(String x)
{
int face = 0;
switch(x)
{
case "aceClubs.jpg":
case "aceDia.jpg":
case "aceHearts.jpg":
case "aceSpades.jpg":
face = 1;
break;
case "eightClubs.jpg":
case "eightDia.jpg":
case "eightHearts.jpg":
case "eightSpades.jpg":
face = 8;
break;
case "fiveClubs.jpg":
case "fiveDia.jpg":
case "fiveHearts.jpg":
case "fiveSpades.jpg":
face = 5;
break;
case "fourClubs.jpg":
case "fourDia.jpg":
case "fourHearts.jpg":
case "fourSpades.jpg":
face = 4;
break;
case "jackClubs.jpg":
case "jackDia.jpg":
case "jackHearts.jpg":
case "jackSpades.jpg":
case "kingClubs.jpg":
case "kingDia.jpg":
case "kingHearts.jpg":
case "kingSpades.jpg":
case "queenClubs.jpg":
case "queenDia.jpg":
case "queenHearts.jpg":
case "queenSpades.jpg":
case "tenClubs.jpg":
case "tenDia.jpg":
case "tenHearts.jpg":
case "tenSpades.jpg":
face = 10;
break;
case "twoClubs.jpg":
case "twoDia.jpg":
case "twoHearts.jpg":
case "twoSpades.jpg":
face = 2;
break;
case "threeClubs.jpg":
case "threeDia.jpg":
case "threeHearts.jpg":
case "threeSpades.jpg":
face = 3;
break;
case "sixClubs.jpg":
case "sixDia.jpg":
case "sixHearts.jpg":
case "sixSpades.jpg":
face = 6;
break;
case "sevenClubs.jpg":
case "sevenDia.jpg":
case "sevenHearts.jpg":
case "sevenSpades.jpg":
face = 7;
break;
case "nineClubs.jpg":
case "nineDia.jpg":
case "nineHearts.jpg":
case "nineSpades.jpg":
face = 9;
break;
}
return face;
}
//shuffles all the cards in the deck
private void shuffle()
{
long seed = System.nanoTime();
Collections.shuffle(allCards, new Random(seed));
}
/**
* Chooses a card at random from the deck. Also removes that card when chosen
* #return randomly chosen card
*/
public ImageIcon getRandomCard()
{
int index = ((int)Math.random() * allCards.size());
return allCards.remove(index);
}
/**
* #return Image of the back of a card
*/
public ImageIcon getBackCard()
{return backCard;}
public static ImageIcon parseImage(String x)
{
if(x.contains("Dia"))
return new ImageIcon("cards/diamonds/"+x);
else
if(x.contains("Clubs"))
return new ImageIcon("cards/clubs/"+x);
else
if(x.contains("Hearts"))
return new ImageIcon("cards/hearts/"+x);
else
if(x.contains("Spades"))
return new ImageIcon("cards/spades/"+x);
return null;
}
//adds all the cards and adds a description to them loaded into memory
private void addCardsAndChangeSize() throws IOException
{
String tempString;
ImageIcon tempIcon;
allCards.clear();
ClassLoader cldr = this.getClass().getClassLoader();
URL imageURL;
for(int i = 0; i < all.length; i++)
{
for(int x = 0; x < clubs.length; x++)
{
tempString = all[i][x];
tempString = "/cards/"+cardFolders[i]+"/"+tempString;
imageURL = cldr.getResource(tempString);
tempIcon = resizeImage(new ImageIcon(imageURL),70,70,false);
tempString = all[i][x];
tempIcon.setDescription(tempString);
allCards.add(tempIcon);
}
}
backCard = resizeImage(new ImageIcon(cldr.getResource(back)),70,70,false);
}
//resizes images
public ImageIcon resizeImage(ImageIcon imageIcon, int width, int height, boolean max)
{
Image image = imageIcon.getImage();
Image newimg = image.getScaledInstance(-1, height, java.awt.Image.SCALE_SMOOTH);
int width1 = newimg.getWidth(null);
if ((max && width1 > width) || (!max && width1 < width))
newimg = image.getScaledInstance(width, -1, java.awt.Image.SCALE_SMOOTH);
return new ImageIcon(newimg);
}
}
I keep getting null pointer exception on the tempIcon = resizeImage(new ImageIcon(imageURL),70,70,false);
Can anyone tell me why this isn't loading the images properly? Reminder i am pre-loading them into memory. My question is not how to make this better i am just simply asking what am i doing wrong with the class loader and stuff like that......
I am somewhat new at java and i know some of this code will look horrible to you but please again i am not asking how to make this code "pro" im just looking for the explanation why its giving me null.
Thanks!
P.S. If you need more pictures of info or w.e. i will try to put that up right away
Your problem is that cldr.getResource(tempString); does not return object but null. Then, something is wrong with tempString. Classloader cannot find this file, so returns null.
Change tempString = "/cards/"+cardFolders[i]+"/"+tempString;
To tempString = "cards/"+cardFolders[i]+"/"+tempString;
You should be using the getResource of Class, not ClassLoader. The getResource method in Class does useful transformations on the path before giving it to the ClassLoader version of the method, like deciding if the path is relative to the class or absolute, and so ClassLoader doesn't expect to see things like / at the start of the path. You can see this clearly in the getResource javadoc.
So i found out the solution i still don't quite understand why this is the answer but here ya go.
This is the revised code and works fine
private void addCardsAndChangeSize() throws Exception
{
String tempString;
ImageIcon tempIcon;
allCards.clear();
URL imageURL;
for(int i = 0; i < all.length; i++)
{
for(int x = 0; x < clubs.length; x++)
{
tempString = all[i][x];
tempString = "/cards/"+cardFolders[i]+"/"+tempString;
imageURL = this.getClass().getResource(tempString);
System.out.println(tempString);
System.out.println(imageURL == null);
tempIcon = resizeImage(new ImageIcon(imageURL),70,70,false);
tempString = all[i][x];
tempIcon.setDescription(tempString);
allCards.add(tempIcon);
}
}
backCard = resizeImage(new ImageIcon(this.getClass().getResource(back)),70,70,false);
}
You have to have that "/cards/" and also you this.getClass().getResource(String res);
Thanks for all your help guys!
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am designing a game in Android/Java and so far everything has gone well. The game shows a random card from a deck of 52 and the user has to determine whether the next card will be higher or lower. I put my switch & case in my main class, and im not sure how to re-run the switch and case statement to draw another card at random.
Below are my classes, I know I dont need this many, but I changed the code around alot since my original in attempt to get this to work. I know the problem is not with my app, its because of my inexperience in android... Check out the code and tell me what you think. Since its a pretty broad question and there may be more than one answer, I will upvote everyone who gives me a relevant answer, weather I use the solution or not.
Thanks,
-Steve
My Main Game Class:
public class Game extends SwarmActivity {
int cardNum;
Deck d = new Deck();
int x = d.shuffle();
String y = String.valueOf(x);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Swarm.init(this, 1388, "1e02a1ecfa9483b7b62e7b32c7e055f3");
TextView t = (TextView) findViewById(R.id.score);
ImageView display = (ImageView) findViewById(R.id.display);
switch (x) {
case 0:
display.setImageResource(R.drawable.c_one);
cardNum = 1;
break;
case 1:
display.setImageResource(R.drawable.c_two);
cardNum = 2;
break;
case 2:
display.setImageResource(R.drawable.c_three);
cardNum = 3;
break;
case 3:
display.setImageResource(R.drawable.c_four);
cardNum = 4;
break;
case 4:
display.setImageResource(R.drawable.c_five);
cardNum = 5;
break;
---------- (5-49) ----------
case 50:
display.setImageResource(R.drawable.c_fiftyone);
cardNum = 51;
break;
case 51:
display.setImageResource(R.drawable.c_fiftytwo);
cardNum = 52;
break;
}
ImageView higher = (ImageView) findViewById(R.id.btn_higher);
ImageView lower = (ImageView) findViewById(R.id.btn_lower);
higher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
lower.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
Deck Class: (originally this was in my game class)
public class Deck {
public int shuffle() {
Shuffle s = new Shuffle();
int[] shuffDeck = s.getShuffle();
int i = 0;
int x = shuffDeck[i];
String y = String.valueOf(x);
return x;
}
}
Shuffle Class: (Originally this was in my game class)
public class Shuffle {
public static int[] getShuffle() {
int[] cards = new int[52];
ArrayList<Integer> cards_objs = new ArrayList<Integer>();
for (int i = 0; i < cards.length; i++) {
cards_objs.add(i);
}
Collections.shuffle(cards_objs);
for (int i = 0; i < cards.length; i++) {
cards[i] = cards_objs.get(i);
}
return cards;
}
}
If you want to replace that big switch-case, then try naming your drawables like card_00.png, card_01.png ... card_51.png. This way you can access your drawable ids much easier using the reflection API (or something else) like this:
int [] cards = new int [52];
Field [] fields = R.drawable.class.getDeclaredFields();
String [] names = new String[52];
for(int i=0; i<fields.length; i++)
if(fields[i].getName().contains("card_"))
names[i] = fields[i].getName();
Arrays.sort(names);
try
{
for(int i=0; i<names.length; i++)
cards[i] = R.drawable.class.getField(names[i]).getInt(null);
}
catch(Exception ex){}
If everything went well, then now you have an array of all the drawable ids of your cards. Now your life is 90% more simple. To set the random card simply use:
//create a Random object, and an integer
//indicating the current card as a member of your class:
Random random = new Random();
int actual = 0;
//then for random card selection:
actual = random.nextInt(52);
display.setImageResource(cards[actual]);
//for getting a higher card:
actual = actual<51 ? actual+1 : actual;
display.setImageResource(cards[actual]);
//for getting a lower card:
actual = actual>0 ? actual-1 : actual;
display.setImageResource(cards[actual]);
How can i load a random image out of 2 ?
I tried this code
final Random rgenerator = new Random();
Integer [] mImageIds =
{
R.drawable.mantrans,
R.drawable.womentrans,
};
Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
gBall1 = BitmapFactory.decodeResource(getResources(), q);
but it did not work...
Please help
this is useful to you..
/////*****Random numbers with out repetation*****//////
final int[] imageViews = {
R.id.imgview11, R.id.imgview12, R.id.imgview13 };
final int[] images = {
R.drawable.i1, R.drawable.i2, R.drawable.i3 };
Random rng = new Random();
List<Integer> generated = new ArrayList<Integer>(maxNoOfImages);
for (int i = 0; i < maxNoOfImages; i++) {
while(true) {
Integer next = rng.nextInt(maxNoOfImages);
if (!generated.contains(next)) {
ImageView iv = (ImageView)findViewById(imageViews[i]);
iv.setImageResource(images[next]);
generated.add(next);
break;
}
}
}
This is kind of a too much for such a simple task. But I haven't really used the Random class. This is an alternative method.
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(R.drawable.mantrans);
ids.add(R.drawable.womentrans);
Collections.shuffle(ids);
gBall1 = BitmapFactory.decodeResource(getResources(), ids.get(0));
You may need to add a bit more id's as getting random in 2 options might not seem much random like pents90 mentioned.