In this, I want to change the images in the order. i.e on 1st click of dice1 itself, dice1 should change then dice2, dice3, dice4, and then again dice1 and soo on till the end of the loop. but whenever I click any image only the image in dice2 changes. The image I click only that should change that too in the predefined order. Can someone please help fix the code.
JAVA FILE
public class MainActivity extends AppCompatActivity{
private ImageView dice1,dice2,dice3,dice4;
private ImageView[] dice = { dice1, dice2, dice3, dice4 };
private Random rng = new Random();
public int i=0,j=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dice[0] = findViewById(R.id.imageView3);
dice[1]= findViewById(R.id.imageView7);
dice[2] = findViewById(R.id.imageView9);
dice[3] = findViewById(R.id.imageView5);
while(j<5){
if(i==4){
i=0;}
dice[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
rollDice();
}
});
j++;
i++;
}
}
private void rollDice(){
int randomNo = rng.nextInt(6)+1;
switch (randomNo){
case 1:
dice[i].setImageResource(R.drawable.one);
break;
case 2:
dice[i].setImageResource(R.drawable.two);
break;
case 3:
dice[i].setImageResource(R.drawable.three);
break;
case 4:
dice[i].setImageResource(R.drawable.four);
break;
case 5:
dice[i].setImageResource(R.drawable.five);
break;
case 6:
dice[i].setImageResource(R.drawable.six);
break;
}
}
Related
So, I tried to call all the methods from overView but is not working, I tried with "view" in the parentheses and then is constantly crashing when I start the app.... Can someone help, this is the whole code. I tried not to include the first four methods but then is not working the way it's suppose to.
public class MainActivity extends AppCompatActivity {
int health = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void checkQuestionOne(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_one_yes:
if(checked)
health += 1;
break;
case R.id.question_one_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionTwo(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_two_yes:
if(checked)
health += 1;
break;
case R.id.question_two_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionThree(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_three_yes:
if(checked)
health += 1;
break;
case R.id.question_three_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionFour(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_four_yes:
if(checked)
health += 1;
break;
case R.id.question_four_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionFive() {
EditText gettingQuestionFive = findViewById(R.id.sleep_hours);
int answerQuestionFive = Integer.parseInt(gettingQuestionFive.getText().toString());
if (answerQuestionFive > 7) {
health += 1;
} else if (answerQuestionFive == 7) {
health += 1;
} else {
health -=1;
}
}
private void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.summary);
orderSummaryTextView.setText(message);
}
public void overView(View view){
checkQuestionOne();
checkQuestionTwo();
checkQuestionThree();
checkQuestionFour();
checkQuestionFive();
String Message = health + " is your score. If is 3 or above, you have a healthy life";
displayMessage(Message);
}
}
I think you have forgot to call the overView() method in the onCreate() method of activity. You can call it like this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Pass your view in argument
overView(View view)
}
In my app I want to randomly pick an image and put it in the center of the screen. After that, animations can be performed, the image will be moved and reset to its origin position afterwards. Then I want to choose a new image of the switch case, but the image always stays the same. How can I fix it?
public class MainActivity extends Activity implements OnGestureListener
{
private ImageView imageView;
float x1,x2;
float y1, y2;
public int sco = 0;
TextView score;
final Random rand = new Random();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageview1);
imageView.setImageResource(getMyRandomResId());
score = (TextView)findViewById(R.id.textView2);
}
int imag = rand.nextInt(4);
int getMyRandomResId() {
switch (imag) {
case 0:
return R.drawable.a;
case 1:
return R.drawable.b;
case 2:
return R.drawable.c;
default:
return R.drawable.d;
}
}
private boolean animationRunning = false;
public boolean onTouchEvent(MotionEvent touchevent)
{
final ViewPropertyAnimator animator = imageView.animate();
switch (touchevent.getAction())
{
case MotionEvent.ACTION_DOWN:
{
x1 = touchevent.getX();
y1 = touchevent.getY();
break;
}
case MotionEvent.ACTION_UP:
{
x2 = touchevent.getX();
y2 = touchevent.getY();
if (!animationRunning) {
//left to right sweep event on screen
if (x1 < x2 && (x2-x1)>=(y1-y2) && (x2-x1)>=(y2-y1)) {
animationRunning = true;
animator.translationX(imageView.getWidth() * 2)
.setDuration(180)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
if(getMyRandomResId() == R.drawable.ballgrue) {
sco++;
}
imageView.setTranslationX(0);
imageView.setImageResource(getMyRandomResId());
animationRunning = false;
}
})
.start();
}
}
}
}
}
}
int getMyRandomResId() {
int imag = rand.nextInt(4);
switch (imag) {
case 0:
return R.drawable.a;
case 1:
return R.drawable.b;
case 2:
return R.drawable.c;
default:
return R.drawable.d;
}
}
the reason you got a same image bcoz of this only
Hope it helps
I am making a game in which you can click on a card to change it randomly to another card. The image file for one card is 370x512 png and it size is more or less 200 kb. My problem is the process in which the imageView changes its picture from one card to another is very slow and lasts almost two seconds. The other problem is that if you click too fast on the card the class crashes. I've tried it already with an ImageButton, with a button and an ImageView and I tried it with 11 ImageViews (there are 11 different cards in the game) who are always there but only one of it is visible. I don't have any clue why the card changing process takes so much time. Here is my code to change the card. This code is with a button and an ImageView:
public class MainActivity extends Activity {
public static String dampfhammerData = "dampfhammerData";
SharedPreferences DampfhammerData;
public int nextCard;
public int lastCard = 0;
public int all=3;
public int buddy=3;
public int dampfhammer=3;
public int frauen=3;
public int links=3;
public int rechts=3;
public int maenner=3;
public int questionmaster=3;
public int regel=3;
public int themenrunde=3;
public int zaehlen=3;
public int deck = 44;
public String version;
ImageView Karte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void changeCard(View view) {
selectCard();
}
public void selectCard(){
lastCard = nextCard;
if(deck > 0) {
Random rand = new Random();
nextCard = (rand.nextInt(10));
if(nextCard != lastCard) {
checkCardDeck();
}else {
selectCard();
}
}else {
Intent intent = new Intent(this, End.class);
startActivity(intent);
}
}
public void checkCardDeck(){
Karte = (ImageView) findViewById(R.id.karte);
switch (nextCard) {
case 0:
if(all > 0){
all--;
deck--;
Karte.setBackgroundResource(R.drawable.all);
}else {
selectCard();
}
break;
case 1:
if(zaehlen > 0){
zaehlen--;
deck--;
Karte.setBackgroundResource(R.drawable.zaehlen);
}else {
selectCard();
}
break;
case 2:
if(buddy > 0){
buddy--;
deck--;
Karte.setBackgroundResource(R.drawable.buddie);
}else {
selectCard();
}
break;
case 3:
if(themenrunde > 0){
themenrunde--;
deck--;
Karte.setBackgroundResource(R.drawable.themenrunde);
}else {
selectCard();
}
break;
case 4:
if(dampfhammer > 0){
dampfhammer--;
deck--;
Karte.setBackgroundResource(R.drawable.dampfhammer);
}else {
selectCard();
}
break;
case 5:
if(links > 0){
links--;
deck--;
Karte.setBackgroundResource(R.drawable.links);
}else {
selectCard();
}
break;
case 6:
if(rechts > 0){
rechts--;
deck--;
Karte.setBackgroundResource(R.drawable.rechts);
}else {
selectCard();
}
break;
case 7:
if(frauen > 0){
frauen--;
deck--;
Karte.setBackgroundResource(R.drawable.frauen);
}else {
selectCard();
}
break;
case 8:
if(maenner > 0){
maenner--;
deck--;
Karte.setBackgroundResource(R.drawable.maenner);
}else {
selectCard();
}
break;
case 9:
if(questionmaster > 0){
questionmaster--;
deck--;
Karte.setBackgroundResource(R.drawable.questionmaster);
}else {
selectCard();
}
break;
case 10:
if(regel > 0){
regel--;
deck--;
Karte.setBackgroundResource(R.drawable.regel);
}else {
selectCard();
}
break;
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Wollen sie das Spiel verlassen?") //
.setMessage("Das aktuelle Spiel wird abgebrochen und sie kehren zum Startbildschirm zurück, wollen sie das wirklich?") //
.setPositiveButton(("Ja"), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton(("Nein"), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.show();
}
}
Thanks for your help!
If your deck of cards consists of 11 cards that each appear four times (I think that's right based on looking at the code), you can create a random shuffle like this:
ArrayList<Integer> deckList = new ArrayList<Integer>();
for (int i=0; i<11; i++) {
deckList.add(i); deckList.add(i); deckList.add(i); deckList.add(i);
}
Collections.shuffle(deckList);
By instead picking a random next card and retrying when it's a repeat, you're using a very inefficient and unpredictable process, especially since the retries are recursive, increasing the size of the call stack.
You will of course have to make other changes to use my deck in your code, but it should be quite a bit faster.
So I'm having an issue with my code when using the android emulator. I get the same error: Throwing OutOfMemoryError "Failed to allocate a 4776816 byte allocation with 2473998 free bytes and 2MB until OOM"
I have a feeling this is due to memory leak as I create objects for each class within each other class and I imagine it's causing some kind of loop error. Is this disallowed in Java? Any help would be much appreciated..
Here is the code:
public class BoardActivity extends AppCompatActivity {
Move move = new Move();
Button buttons[] = new Button[16];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_board);
move.newGame();
buttons[0] = (Button)findViewById(R.id.button1);buttons[0].setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
move.makeMove(move.cups.get(0));
updateButtons();
}});
buttons[1] = (Button)findViewById(R.id.button2);buttons[1].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(1));
updateButtons();
}
});
buttons[2] = (Button)findViewById(R.id.button3);buttons[2].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(2));
updateButtons();
}
});
buttons[3] = (Button)findViewById(R.id.button4);buttons[3].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(3));
updateButtons();
}
});
buttons[4] = (Button)findViewById(R.id.button5);buttons[4].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(4));
updateButtons();
}
});
buttons[5] = (Button)findViewById(R.id.button6);buttons[5].setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
move.makeMove(move.cups.get(5));
updateButtons();
}
});
buttons[6] = (Button)findViewById(R.id.button7);buttons[6].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(6));
updateButtons();
}
});
buttons[7] = (Button)findViewById(R.id.button8);buttons[7].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
updateButtons();
}
});
buttons[8] = (Button)findViewById(R.id.button9);buttons[8].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(8));
updateButtons();
}
});
buttons[9] = (Button)findViewById(R.id.button10);buttons[9].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(9));
updateButtons();
}
});
buttons[10] = (Button)findViewById(R.id.button11);buttons[10].setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
move.makeMove(move.cups.get(10));
updateButtons();
}
});
buttons[11] = (Button)findViewById(R.id.button12);buttons[11].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(11));
updateButtons();
}
});
buttons[12] = (Button)findViewById(R.id.button13);buttons[12].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(12));
updateButtons();
}
});
buttons[13] = (Button)findViewById(R.id.button14);buttons[13].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(13));
updateButtons();
}
});
buttons[14] = (Button)findViewById(R.id.button15);buttons[14].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
move.makeMove(move.cups.get(14));
updateButtons();
}
});
// Still have bug with this button - needs to be sorted
buttons[15] = (Button)findViewById(R.id.button16);buttons[15].setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
updateButtons();
}
});
updateButtons();
}
public void updateButtons(){
for(int i=0; i<buttons.length; i++){
buttons[i].setText(move.cups.get(i).toString());
}
}
}
Player class:
public class Player extends Move{
Random rand = new Random();
BoardActivity board = new BoardActivity();
/**public void setScoreCups(){
if(returnCurrentPlayer()==1){
oppositionScoreCup = cups.get(16);
scoreCup = cups.get(8);
}else{
oppositionScoreCup = cups.get(8);
scoreCup = cups.get(16);
}
}**/
public void setNextPlayer(){
if(returnCurrentPlayer()==1) {
setTurnPlayer(2);
}else if(returnCurrentPlayer()==2){
setTurnPlayer(1);
}
}
public int returnCurrentPlayer(){
if(board.buttons[5].isEnabled()){
return 1;
}else{
return 2;
}
}
public void setRandomPlayer(){
boolean b = rand.nextBoolean();
if(b){
setTurnPlayer(1);
}else{
setTurnPlayer(2);
}
}
public void setTurnPlayer(int n){
if(n==1) {
for (int i = 1; i < 8; i++) {
board.buttons[i].setEnabled(true);
}
for (int i = 9; i < 16; i++) {
board.buttons[i].setEnabled(false);
}
}else if(n==2){
for(int i=1; i<8; i++){
board.buttons[i].setEnabled(false);
}
for(int i=9; i<16; i++){
board.buttons[i].setEnabled(true);
}
}
}
public void setPlayer() {
if ((move.currentCup.pebbleCount == 0) && (move.currentCup != move.scoreCup)) {
Log.d("makeMove.java", "print cup index" + move.cups.indexOf(move.currentCup));
//emptyCupSwitch(currentCup);
move.currentCup.increasePebbleCount();
}
if (move.currentCup == move.scoreCup) {
move.currentCup.increasePebbleCount();
setTurnPlayer(move.currentPlayer);
} else if (move.currentCup != move.scoreCup) {
move.currentCup.increasePebbleCount();
setNextPlayer();
}
}
//needs to be changed
public static int score=0;
public void setScore(int n){
score = n;
}
}
And Move class:
public class Move extends Game{
Player player = new Player();
public Cup oppositionScoreCup; public Cup scoreCup;
int i; int currentPlayer; int cupValue;
int currentIndex; int lastCupIndex = currentIndex + cupValue - 1;
Cup currentCup;
public List<Cup> cups;
public void newGame() {
cups = new ArrayList<>();
//Reset all cups
for (int i = 0; i < 16; i++) {
Cup cup = new Cup(7);
cups.add(i, cup);
}
}
//Returns the cup following the one entered in the parameters
public Cup getNextCup(Cup cup) {
if (cups.indexOf(cup) == 15) {
return cups.get(0);
} else {
return cups.get(cups.indexOf(cup) + 1);
}
}
//Emptys current cup and switches pebbles to opposite side
public void emptyCupSwitch(Cup cup) {
Cup oppCup;
int index = cups.indexOf(cup);
switch(index) {
case 1:
oppCup = cups.get(15);
cups.get(1).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
break;
case 2:
oppCup = cups.get(14);
cups.get(2).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
break;
case 3:
oppCup = cups.get(13);
cups.get(3).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
break;
case 4:
oppCup = cups.get(12);
cups.get(4).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 5:
oppCup = cups.get(11);
cups.get(5).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 6:
oppCup = cups.get(10);
cups.get(6).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 7:
oppCup = cups.get(9);
cups.get(7).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 9:
oppCup = cups.get(7);
cups.get(9).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 10:
oppCup = cups.get(6);
cups.get(10).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 11:
oppCup = cups.get(5);
cups.get(11).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 12:
oppCup = cups.get(4);
cups.get(12).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 13:
oppCup = cups.get(3);
cups.get(13).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 14:
oppCup = cups.get(2);
cups.get(7).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
case 15:
oppCup = cups.get(1);
cups.get(7).pebbleCount += oppCup.pebbleCount;
oppCup.emptyCup();
}
}
//Method for Clicking Cup - Basic move - Skips oppositonScoreCup
public void makeMove(Cup cup) {
cupValue = cup.returnPebbleCount();
currentIndex = cups.indexOf(cup);
currentCup = getNextCup(cup);
cup.emptyCup();
for (i = currentIndex; i < currentIndex + cupValue; i++) {
if (i == lastCupIndex) {
player.setPlayer();
} else if (currentCup == oppositionScoreCup) {
currentCup = getNextCup(currentCup);
} else if (currentCup != oppositionScoreCup) {
currentCup.increasePebbleCount();
currentCup = getNextCup(currentCup);
}
}
if(checkGameOver()){
gameOver();
}
}
}
You are running out of memory because your code will run recursively and create an infinite number of objects of BoardActivity, Move and Player.
How? Well, when the BoardActivity class is initialized, the line
Move move = new Move();
will create new Move object. This, in turn will result in the execution of the line
Player player = new Player();
from inside the Move class. This will spawn a new Player object which contains the line
BoardActivity board = new BoardActivity();
Now this will create another BoardActivity object and this takes us back to the beginning creating an endless cycle of object spawning.
Simply put, BoardActivity->Move->Player->BoardActivity->Move->Player....
I'm guessing the AppCompatActivity is an android activity. Android activities are pretty heavy and allocates some good amount of heap memory when initialized. This is basically why you are running out of memory so quickly.
You shouldn't be creating an activity this way. Either create one and start from the main activity or load it as the default activity using the AndroidManifest
Also instead of creating a separate OnClickListener for each button, it would be better to create a single OnClickListener and check button ids using if statements to determine which button was clicked.
when you click the color should change to another
but it doesnt work!
My code:
#
public class CreateActivity extends Activity {
TableLayout table;
Integer i;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout)findViewById(R.id.myTable);
Button left = (Button) findViewById(R.id.buttonLeft);
Button right = (Button) findViewById(R.id.buttonRight);
TextView color = (TextView) findViewById(R.id.text);
i=0;
right.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
i++; //+1
}
});
//COLOR
switch(i){
case 1: table.setBackgroundColor(Color.RED); break;
case 2: table.setBackgroundColor(Color.rgb (255, 127, 0) ); break;
case 3: table.setBackgroundColor(Color.YELLOW); break;
case 4: table.setBackgroundColor(Color.GREEN) ; break;
case 5: table.setBackgroundColor(Color.rgb (0,191,255) ); break;
case 6: table.setBackgroundColor(Color.BLUE ); break;
case 7: table.setBackgroundColor(Color.rgb (160,32,240) ); break;
}
}
}
When the button is clicked, you're incrementing i - but you won't be running the switch/case statement again. If you look in the debugger you'll find that the variable value is changing, but you haven't instructed any part of the display to change.
You should put that common logic in a separate method which is called both from the onCreate method and the OnClickListener. For example:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout)findViewById(R.id.myTable);
Button left = (Button) findViewById(R.id.buttonLeft);
Button right = (Button) findViewById(R.id.buttonRight);
TextView color = (TextView) findViewById(R.id.text);
i=0;
right.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
i++;
// Cycle round
if (i == 8) {
i = 1;
}
applyBackgroundColor();
}
});
applyBackgroundColor();
}
private void applyBackgroundColor() {
switch(i) {
// TODO: Consider what you want to do when i is 0...
case 1: table.setBackgroundColor(Color.RED); break;
case 2: table.setBackgroundColor(Color.rgb(255, 127, 0)); break;
case 3: table.setBackgroundColor(Color.YELLOW); break;
case 4: table.setBackgroundColor(Color.GREEN); break;
case 5: table.setBackgroundColor(Color.rgb(0,191,255)); break;
case 6: table.setBackgroundColor(Color.BLUE); break;
case 7: table.setBackgroundColor(Color.rgb(160,32,240)); break;
}
}
There are various other things I'd change about this code, but that should at least get you over this hump.