Modification de la classe Network pour qu'elle prenne en compte le serveur. Et ajout de la permission d'acces a Internet

This commit is contained in:
Bertrand BRUN 2011-02-01 03:59:34 +01:00
parent 0b74230480
commit bb96b13792
2 changed files with 50 additions and 19 deletions

View File

@ -17,4 +17,5 @@
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

View File

@ -1,10 +1,12 @@
package org.pticlic.model;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
public class Network {
@ -32,7 +34,8 @@ public class Network {
this.serverURL = serverURL;
}
public Game getGames(int nbGames) {
public Game getGames(int nbGames) {
Game game = null;
try {
URL url = new URL(this.serverURL);
URLConnection connection = url.openConnection();
@ -41,32 +44,59 @@ public class Network {
connection.addRequestProperty("mode", mode.value());
Gson gson = new Gson();
// JsonReader reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// Game game = gson.fromJson(reader, Game[].class);
JsonReader reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
// TODO : A enlever sert juste pour les tests
String json =
"{" +
" id: 1234," +
" cat1: 11," +
" cat2: 23," +
" cat3: -1," +
" cat4: -1, " +
" center: { id: 555, name: \"chat\" }, " +
" cloud: [" +
" { id: 123, name: \"souris\" }," +
" { id: 111, name: \"lait\" }," +
" { id: 345, name: \"machine à laver\" }" +
" ]" +
"}";
Game game = gson.fromJson(json, Game.class);
// FIXME : Attention lorsque l'on pourra vraiment recupere plusieur partie, il faudra changer ce qui suit.
reader.beginArray();
while (reader.hasNext()) {
game = makeGame(reader, gson);
}
reader.endArray();
reader.close();
return game;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private Game makeGame(JsonReader reader, Gson gson) throws IOException {
int id = -1;
int cat1 = -1;
int cat2 = -1;
int cat3 = -1;
int cat4 = -1;
Game.Word center = null;
Game.Word[] cloud = null;
reader.beginObject();
while (reader != null && reader.hasNext()) {
String name = reader.nextName();
if (name.equals("id")) {
id = reader.nextInt();
} else if (name.equals("cat1")) {
cat1 = reader.nextInt();
} else if (name.equals("cat2")) {
cat2 = reader.nextInt();
} else if (name.equals("cat3")) {
cat3 = reader.nextInt();
} else if (name.equals("cat4")) {
cat4 = reader.nextInt();
} else if (name.equals("center")) {
center = gson.fromJson(reader, Game.Word.class);
} else if (name.equals("cloud")) {
cloud = gson.fromJson(reader, Game.Word[].class);
} else {
reader.skipValue();
}
}
reader.endObject();
return new Game(id, cat1, cat2, cat3, cat4, center, cloud);
}
public boolean sendGame(Game game) {
throw new UnsupportedOperationException();
}