Can Android Studio remove multiple elements from an array? How? - java
I'm practice developing an app but I met a problem. I want remove two elements from an array but android studio only can remove one and if I adding one more the app will crash, below is my code and now I only put one code to remove the first element and i need to remove last element otherwise the choice for answer will mix the array.
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
{"quadrilateral","quadrilateral","triangle","heptagon","pentagon","hexagon","decagon","Which one is the green polygon just now ?"},
{"triangle","triangle","heptagon","quadrilateral","pentagon","octagon","decagon","Which one is the red polygon just now ?"},
{"circle","circle","triangle","quadrilateral","pentagon","nonagon","decagon","Which one is the black polygon just now ?"},
{"star","star","circle","octagon","pentagon","hexagon","decagon","Which one is the brown polygon just now ?"},
{"decagon","decagon","triangle","circle","pentagon","hexagon","star","Which one is the pink polygon just now ?"},
{"heptagon","heptagon","decagon","quadrilateral","pentagon","hexagon","star","Which one is the yellow polygon just now ?"},
{"hexagon","hexagon","decagon","heptagon","pentagon","octagon","star","Which one is the sky blue polygon just now ?"},
{"nonagon","nonagon","circle","quadrilateral","triangle","hexagon","star","Which one is the orange polygon just now ?"},
{"pentagon","pentagon","nonagon","octagon","heptagon","hexagon","circle","Which one is the purple polygon just now ?"},
{"octagon","octagon","triangle","quadrilateral","pentagon","hexagon","star","Which one is the dark blue polygon just now ?"}
};
public void Show_Next_Quiz(){
Random random = new Random();
int Random_Num = random.nextInt(quizArray.size());
ArrayList<String> quiz = quizArray.get(Random_Num);
Question1.setText(quiz.get(7));
iV1.setImageResource(
getResources().getIdentifier(quiz.get(0), "drawable", getPackageName())
);
iV2.setImageResource(
getResources().getIdentifier(quiz.get(0), "drawable", getPackageName())
);
iV3.setImageResource(
getResources().getIdentifier(quiz.get(0), "drawable", getPackageName())
);
iV4.setImageResource(
getResources().getIdentifier(quiz.get(0), "drawable", getPackageName())
);
iV5.setImageResource(
getResources().getIdentifier(quiz.get(0), "drawable", getPackageName())
);
iV6.setImageResource(
getResources().getIdentifier(quiz.get(0), "drawable", getPackageName())
);
Right_Answer = quiz.get(1);
quiz.remove(0);
//quiz.remove(7);
Collections.shuffle(quiz);
ans1.setText(quiz.get(1));
ans2.setText(quiz.get(2));
ans3.setText(quiz.get(3));
ans4.setText(quiz.get(4));
ans5.setText(quiz.get(5));
ans6.setText(quiz.get(6));
quizArray.remove(Random_Num);
}
Your program is crash because you're trying to remove an item from the List by using an incorrect item position.
For example, assume that you have an ArrayList with size of 7:
ArrayList<String> quizzes = new ArrayList<>(7);
the quiz items from quizzes will be in 0 - 6 range of index position. When you're removing the first item with:
quizzes.remove(0);
the quizzes size is now 6. Now you can only access the items from 0 to 5 index position. It will gives error when you're trying to remove an item with item position beyond that. So, the following code won't work and gives you a crash:
quizzes.remove(7);
because you're trying to access a non-exist item position.
So, you can't depends on the item position to remove the item in your case. You can use public boolean remove(Object o) instead.
quizzes.remove("triangle");
Probably what you need is an another ArrayList for ansX views to match the size of the questions. Something like this:
int sizeOfTheQuiz = 6;
ArrayList<String> quizzes = new ArrayList<>(sizeOfTheQuiz);
ArrayList<TextView> tvAnswers = new ArrayList<>();
tvAnswers.add(ans1);
tvAnswers.add(ans2);
tvAnswers.add(ans3);
tvAnswers.add(ans4);
tvAnswers.add(ans5);
tvAnswers.add(ans6);
// size of the quizzes must not larger than tvAnswers
for(int i = 0; i < quizzes.size(); i++) {
tvAnswers.get(i).setText(quizzes.get(i));
}
Related
Animate multiple views using the same Animation
I have a simple animator file: <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="#android:anim/accelerate_decelerate_interpolator" android:ordering="sequentially" > <objectAnimator android:duration="1000" android:propertyName="x" android:repeatCount="1" android:repeatMode="reverse" android:valueTo="-50" android:valueType="floatType" /> Basically this takes a component and slides it along the X-axis by 50dp to the left. I've successfully attached this to ONE component, and it works flawlessly, but when I try to attach it to multiple components at once, the animation only works for the final component. For Example: I have 5 cards. The AI enemy picks a random card from it's hand. But I would like to animate the enemy "picking" the card. This is where the animation comes into play. So something like this: AnimatorSet cardSet = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.pick_card); for(int i=0; i<enemyCards.size(); i++){ cardSet.setTarget(enemyCards.get(i)); cardSet.start(); } The goal here, would be to loop through each card in the array and slide it out on the X axis. But the animation only occurs on the final card (the 5th card in the array) Additionally (THIS IS BOLD FOR A REASON, people do not read large paragraphs anymore, and someone keeps editing my formatting) - I would like to have a delay each time the card slides out. So the loop should be something like: loop{ animate card 1 delay } OR the animator file should be something like android:delay="100" Ive been trying with little success
You can collect your views in some viewgroup and than animate just parent view so all child views animated ?
This a sketch code written in text editor, it may have syntax errors, but you'll get the concept: AnimatorSet cardSet = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.anim.pick_card); List<AnimatorSet> animators = new ArrayList<>(enemyCards.size()); for (int i = 0, size = animators.size(); i < size; ++i) { animators.add(cardSet.clone()); } final int step = 100; int delay = 0; for (int i = 0, size = enemyCards.size(); i < size; ++i) { AnimatorSet set = animators.get(i); set.setTarget(enemyCards.get(i)); set.setStartDelay(delay); delay += step; set.start(); }
Avoid dynamic views from overlapping
I am developing an app that requires multiple buttons to be created dynamically (onCreate of MainActivity class). Each button has a dimension of 100x100dp. Here's the code: for (int i = 0; i < count; i++) { buttons[i] = new Button(this); RelativeLayout ll = (RelativeLayout)findViewById(R.id.maincontainer); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); buttons[i].setY(i * 150); // should be random buttons[i].setX(i * 120); // should be random String temp = Character.toString(input.charAt(i)); buttons[i].setText(temp); buttons[i].setOnClickListener(this); buttons[i].setId(i); test1.setText(Integer.toString(buttons[i].getId())); ll.addView(buttons[i],lp); } The position of these buttons should be completely random within the layout which can be easily achieved by generating random values for x and y coordinates. But I need the buttons not to overlap other buttons. Also due to 100x100dp dimension, sometimes the previously generated buttons are being partially overlapped by new ones.
You can actually figure this out programatically. Keep the co-ordinates of the views that you generate stored in a list. Then simply compare the co-ordinates to see if the new view intersects. You can use the following for a visualisation: http://silentmatt.com/rectangle-intersection/ I hope you try writing code than copying it from someplace. :) A SO link to help you out: Determine if two rectangles overlap each other?
android java array of paint
i am making a game and i trying to make bitmaps dissapear or appear anyway for some reason when i use paint as 1 object it works but when i add a array paint(fro each bitmap) it crashes here is the lines i used with it: //in MainActivity class Paint[] paintanswer; //in oncreate paintanswer=new Paint[answerlength]; //in the draw func for(int i=0;i<answerlength;i++){ paintanswer[i].setAlpha(answeralpha[i]); canvas.drawBitmap(answerbitmapscaled[i],(float) (((cwidth/2)-((answerlength*answersize)/4)-answersize/4)+i*(answersize/2)),(float) (cwidth/2), paintanswer[i]); the answer length is the length i get from other activity accordingly i set the array
An array in Java is just a container with a certain amount of slots for elements of a certain type. In your case a container that can store for example 20 Paint elements, however, it is completely empty. You have to fill the array with elements if you want to use them later on: paintanswer = new Paint[answerlength]; for (int i = 0; i < answerlength; i++) paintanswer[i] = new Paint();
LibGdx: Table not displayed correctly
I have a table in libgdx which is supposed to have 6 buttons, organised into 2 rows. Here's my code: elementsTable.clear(); String[] colors = new String [6]; colors[0] = "red"; colors[1] = "orange"; colors[2] = "yellow"; colors[3] = "purple"; colors[4] = "blue"; colors[5] = "green"; String category = currentCategory.name(); category = category.substring(0, category.length()-1).toLowerCase(); //removes the last character because otherwise there would be an extra 's' int count = 0; for(String color : colors) { ButtonStyle buttonStyle = new ButtonStyle(); buttonStyle.up = cellsSkin.getDrawable(category + "_" + color); Button button = new Button(buttonStyle); button.addListener(toolBoxListener); button.setName(category + "_" + color); button.setSize(toolBoxButtonSize, toolBoxButtonSize); elementsTable.add(button).pad(toolBoxButtonPadding); count ++; if (count == Math.ceil((colors.length/2d))) elementsTable.row(); } That's the filling. My buttons are of 6 different colors so I loop over the array with the color names to access the skin to get the drawable for the buttons. This part seems to work because when I debug and look at the table, it has the 6 buttons in there with the right size. Then I set the position and size of my table and add it to the stage.: elementsTable.setSize(toolBoxWidth, 500/(float)(3*toolBoxButtonSize+6*toolBoxButtonPadding)*elementsTable.getHeight()); elementsTable.setPosition(195, 30); stage.addActor(elementsTable); The stage has an orthographic camera set that should scale things down just fine. However, what I get is this: Another strange thin is that when I look at the table's height and width in debug mode, it says 0 even thoug there are elements in it that all have the corrct size. Can anyone help me? If you have any further questions on the problem, please ask! I tried to give a detailed description, but I am happy to answer your questions.
It seemsits just the position. 30 is too low for the Y: elementsTable.setPosition(195, 30); Try 150 for example: elementsTable.setPosition(195, 150); Remember the coordinate system that Libgdx (and OpenGL) use is with Y going up.
How can I attach images to 2 variables in a card game?
I wrongly worded my last question so I'm going to retry this. I am making a card game in java, and currently I have the code to print 4 random cards in an arraylist for x number of players. I am using slick 2d and currently have a menu and a play state. I currently have 2 variables connected to each card, a ranging from 0-3, and b ranging from 0-12. How can I display an image in the play state that will relate back properly to these 2 variables? (ex. instead of displaying ace of spades, it displays a picture of the ace of spades) Code: Deck () { cards = new ArrayList < > (); for (int a = 0 ; a <= 3 ; a++) { for (int b = 0 ; b <= 12 ; b++) { cards.add (new Card (a, b)); } } } This is the function to draw a card from a deck public Card PlayerCardDraw () { Random generator = new Random (); int index = generator.nextInt (cards.size ()); return cards.remove (index); } and this is the function that uses the above function to add a card to player 1's hand. I made this to separate each player's hand of cards. public ArrayList <Card> p1Hand; public ArrayList <Card> P1CardDraw () { p1Hand = new ArrayList < > (); p1Hand.add (PlayerCardDraw ()); return p1Hand; } I mentioned I'm using slick 2d, so I assume I won't have to post any of that code.
If I were you, I would rewrite/append the Card class to attach an image on initialisation. Create an image in a common directory, and encode it a-bb.* for an example, and create a public image constant for that particular card. then it would be as simple as calling a simple getter to display the image.