Reputation: 26
I've been trying to make a multiplayer, turn-based app, and so far things have been going smoothly: My app can communicate with a local server, and retrieve information from it. Now when I try to put that information I recieved into an arraylist, I get no errors, but the arraylist stays empty, which causes my app to crash when I call myArrayList.get(i).
Here is the code that sets the array:
I BELIEVE THE PROBLEM IS SETTING THE ARRAY BELOW
//The "i" below is the iterator used for the index
for (int i = 1; i < getSharedPreferences("INFO", MODE_PRIVATE).getInt("numberOfGames", 0) + 1; i++) {
try {
SharedPreferences s = getSharedPreferences("INFO", MODE_PRIVATE);
SharedPreferences.Editor e = s.edit();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("gameid", s.getString("gameID" + i, null)));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
REFRESH_URL, "POST", params);
success = json.getInt("success");
Log.i("LOGI", "Success: " + success);
if (success == 1) {
Log.i("LOGI", "**********GAME #" + s.getString("gameID" + i, null) + "**********");
Log.i("LOGI", "PLAYER1: " + json.getString("player1"));
Log.i("LOGI", "PLAYER2: " + json.getString("player2"));
Log.i("LOGI", "Score1: " + json.getString("score1"));
Log.i("LOGI", "Score2: " + json.getString("score2"));
Log.i("LOGI", "Turn: " + json.getString("turn"));
Log.i("LOGI", "Game Chosen: " + json.getString("gameChosen"));
//EVERYING BELOW IS THE PROBLEM
player1.add(i, json.getString("player1"));
player2.add(i, json.getString("player2"));
score1.add(i, Integer.parseInt(json.getString("score1")));
score2.add(i, Integer.parseInt(json.getString("score2")));
turn.add(i, Integer.parseInt(json.getString("turn")));
gameChosen.add(i, Integer.parseInt(json.getString("gameChosen")));
}
Here is the code that gets the array
private void drawCurrentGames(Canvas canvas){
String player1;
String player2;
String opponent;
int score1;
int score2;
Log.i("LOGI", "WOERKIGN");
for(int i=0; i<Main.games; i++){
//The app crashes here
player1 = Main.player1.get(i);
player2 = Main.player2.get(i);
score1 = Main.score1.get(i);
score2 = Main.score2.get(i);
}
}
When an iterator is not used to set or get the arraylist, everything is fine, but when it is the app crashes
Upvotes: 0
Views: 290
Reputation: 2509
Your iterator that adds items to the array starts at 1. When you call the add(int, Object)
method of an arraylist, the object being added is added at the index of the first parameter.
So the first item to be added is being added at index 1. When you go to read from that array list, you're starting at 0. There's nothing at index 0, which is why your app is crashing.
Upvotes: 1