I have an integer ArrayList and several buttons. Each button corresponds to an index of the ArrayList and I want to display the value of each button’s corresponding index as its text. I have everything working with button behavior, etc. The problem is when I go to swap a button’s value (index value) with another it will start to display 0s for every value I swap it with. I am always going to be swapping the 0 with something else.
So if I have buttons: b1, b2, b3 with values 0, 1, 2 respectively and I swap the values of b1 and b2. The result becomes 0, 0, 2. This is the swapping function:
public static void swap(ArrayList<Integer> list, int firstInd, int secondInd) {
int temp = list.get(firstInd);
list.set(firstInd, list.get(secondInd));
list.set(secondInd, temp);
}
This swap method works, I have tested it independently using print statements, etc. and there are no duplicate 0s and all of the rest of the numbers remain in the list.
Here is the relevant code:
// class declaration
static ArrayList<Integer> numList = new ArrayList<Integer>();
// onCreate
// initialize ArrayList
// displays initial values on buttons
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.first: {
switchButtonValues(R.id.first);
b1.setText(String.valueOf(numList.get(0)));
updateButtonStates();
break;
}
case R.id.second: {
switchButtonValues(R.id.second);
b2.setText(String.valueOf(numList.get(1)));
updateButtonStates();
break;
}
// etc for all buttons
public static void switchButtonValues(int buttonNum) {
switch(buttonNum) {
case R.id.first: {
if(numList.get(1) == 0) {
swap(numList, 0, 1);
} else if (numList.get(3) == 0) {
swap(numList, 0, 3);
} else {
}
break;
}
case R.id.second: {
// etc. for the buttons
The buttons displaying the initial values is correct. So I know the ArrayList is getting initialized properly. The problem occurs when the swapping occurs. All of the values are getting overwritten with 0 somehow.
Even though 0s are overwriting the other values, the button behavior is working correctly because it knows where the “real” 0 is. I have cleaned the project too.
Why is this happening? Anyone have any ideas?
I did an example, I hope it’s near what you expect:
And here is my layout:
that’s worked just fine, and really quite a funny when you shuffle the places and try to put then in order… hehehe
It’s simple and was one good idea for a game 😀 (I will do some sort of this genre and let see what happens)
I think that’s possible to better the code, I had suspect of this part of your code:
I thinked you switch the values, and next set the text with the numList value of that position, but, you had changed with the 0, isn’t? Maybe it’s your problem, try put the line that set the text before the switch…
cya,
Bertan.