Rien de spécial
Le blog de Régis

Ajout d’incident

J’ai passé 2h30 à compléter mon application Android pour http://incidents-transports.com (qui a changé de nom aujourd’hui)

J’ai ajouté une nouvelle activité pour rapporter un nouvel incident.

Il me fallait donc un référentiel des lignes existantes. Je n’ai pas fait compliqué, et ai codé ce référentiel en dur. Grosso-modo c’et une Hashmap qui fait:

<br /> "Metro" : {"1", "2", "3", "3bis", etc.},<br /> "RER": {"A", "B", "C", "D", "E"}<br />

Puis j’ai défini l’interface utilisateur. Un peu comme Benoît sur iPhone, j’ai mis un premier Spinner qui permet de choisir le type de ligne (« Métro », « RER », etc.) et un second qui permet de choisir la ligne exacte.

Spinner spinnerLineName = (Spinner) findViewById(R.id.SpinnerLineName);

public void onItemSelected(AdapterView< ?> parentAdapter,
					  
View selectedItemView, int position, long id) {
				  
lineType= parentAdapter.getItemAtPosition(position).toString();
				  
String[] linenames = TransportationProvider.getLines(lineType);
				  
ArrayAdapter<string> adapter = new ArrayAdapter</string><string>(
						  
parentAdapter.getContext(), R.layout.spinnerlinename, linenames);
				  
spinnerLineName.setAdapter(adapter);
			  
}

Et pour finir, j’ai ajouté une méthode post(Incident incident) sur mon IncidentProvider.

Dans la journée, Olivier Girardot, m’a donné l’API pour poster. Il m’a fait peur parce que l’ajout d’un incident ne peut se faire qu’en JSON. Mais miracle, Android gère très simplement le JSON.

	  
public static void post(Incident newIncident) throws JSONException {
		  
JSONObject json=new JSONObject();
		  
json.put(« line_name »,newIncident.ligne);
		  
json.put(« reason », newIncident.reason);
		  
json.put(« source », « rds »);//TODO
		  
String req=json.toString();

URI uri= new URI(DEFAULT\_ADD\_SERVICE_URL);

HttpClient httpClient = new DefaultHttpClient();
		  
HttpPost httpPost = new HttpPost(uri);
		  
StringEntity body;
		  
try {
			  
body = new StringEntity(req);
			  
httpPost.setEntity(body);
			  
HttpResponse response = httpClient.execute(httpPost);
		  
} catch (Exception e) {
			  
// TODO Auto-generated catch block
			  
e.printStackTrace();
		  
}
	  
}