Programmation Android

Fermé
LY - 21 févr. 2013 à 11:57
 LY - 21 févr. 2013 à 16:43
Bonjour,
je suis entrain de développer une application sous Android qui permet d'envoyer des images sur un serveur. Mon code n'a pas d'erreurs mais quand je lance mon application elle s'arrête tout d'un coup.et j'ai comme tag
error in http connection android.os.networkonmainthreadexception.
Merci d'avance.



A voir également:

1 réponse

scinarf Messages postés 1119 Date d'inscription samedi 18 novembre 2006 Statut Membre Dernière intervention 25 septembre 2014 252
21 févr. 2013 à 15:51
Bonjour,

Serait il possible d'avoir le code, et le fichier XML correspondant au layout ? Sinon je vais avoir du mal pour aider.
0
Bonjour, voici le code:
package com.androidhive.jsonparsing;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.androidhive.jsonparsing.R;
import com.androidhive.jsonparsing.SingleMenuItemActivity;
import com.androidhive.jsonparsing.R.id;
import com.androidhive.jsonparsing.R.layout;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class ListePatient extends ListActivity {

	// url du fichier json
	private static String url = "http://10.18.55.82/Android/reponse2.json";
	
	//url du serveur
	private static String urlphp = "http://10.18.55.82/Android/patient.php"; 
	
	// Noms JSON
	private static final String TAG_CONTACTS = "contacts";	  
	private static final String TAG_NAME = "name";  
	private static final String TAG_IPP = "ipp";
	private static final String TAG_BIRTH = "birth"; 
	private static final String TAG_SEX = "sex";
	private static final String TAG_YEAR = "year";
	private static final String TAG_MONTH = "month";
	private static final String TAG_DAY = "day";
	
	final String EXTRA_DAY = "day";
	final String EXTRA_MONTH = "month";
	final String EXTRA_YEAR = "year"; 
	final String EXTRA_PATIENT = "patient"; 
	final String EXTRA_BOUTON = "bouton";
	
	//barre de progression 
	public ProgressDialog progressDialog; 
	

	
	
	// contacts JSONArray
	JSONArray contacts = null;
	InputStream inputStream;
	
	//tentative de barre de progression, à finaliser avec un thread
private void traitementDesDonnees() {
		
		// On ajoute un message à notre progress dialog
		progressDialog.setMessage("Chargement en cours");
		// On affiche notre message
		progressDialog.show();
}
// barrre de progresssion avec pourccentage
/*private void traitementDesDonneesAvecPourcentage() {
		
		// On ajoute un message à notre progress dialog
		progressDialog.setMessage("Envoie données vers le PACS");
		// On donne un titre à notre progress dialog
		progressDialog.setTitle("Veuillez Patientez SVP");
		// On spécifie le style 
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		// On spécifie le maximum
		progressDialog.setMax(10);
		// On affiche notre message
		progressDialog.show();
		
		new Thread(new Runnable() {
			public void run() {
				// Boucle de 1 a 10
				for (int i = 0; i < 10; i++) {
					try {
						// Attends 500 millisecondes
						Thread.sleep(500);
						// On change la valeur de la progression
						progressDialog.setProgress(i+1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				// A la fin du traitement, on fait disparaitre notre message
				progressDialog.dismiss();
			}
		}).start();	
	}*/

	
	//fonction d'envoi des informations vers le serveur
	private void send(String jour, String mois, String annee, String patient, String bouton){ 
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("jour",jour));
		nameValuePairs.add(new BasicNameValuePair("mois",mois));
		nameValuePairs.add(new BasicNameValuePair("annee",annee));
		nameValuePairs.add(new BasicNameValuePair("patient",patient));
		nameValuePairs.add(new BasicNameValuePair("bouton",bouton));		 
		
		try{			
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new	HttpPost("http://10.18.55.82/Android/patient.php");
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			inputStream = entity.getContent();
			
		}catch(Exception e){
			Log.e("log_tag", "Error in http connection "+e.toString());
		}		
	}
		
		 
	@Override 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState); 
		progressDialog = new ProgressDialog(this);
		Intent in = getIntent();
		
		//récupération des infos de la date
	    String jour = in.getStringExtra(EXTRA_DAY);
	    String mois = in.getStringExtra(EXTRA_MONTH);
	    String annee = in.getStringExtra(EXTRA_YEAR);
	    String patient = in.getStringExtra(EXTRA_PATIENT);
	    String bouton = in.getStringExtra(EXTRA_BOUTON);
	    
	    Log.d("alerte", jour);
	    Log.d("alerte", mois);
	    Log.d("alerte", annee);
	    Log.d("alerte", patient);
	    Log.d("alerte", bouton);
	   
	    
	    send(jour, mois, annee, patient, bouton);
	    
	        
        //tentative barre de progression
	    
		setContentView(R.layout.liste_patient);
		
		// Hashmap for ListView
		
		ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
					
		// Creating JSON Parser instance
		JSONParser jParser = new JSONParser();

		// getting JSON string from URL
		JSONObject json = jParser.getJSONFromUrl(url);

		try { 
			// Getting Array of Contacts
			contacts = json.getJSONArray(TAG_CONTACTS);
			// looping through All Contacts
			for(int i = 0; i < contacts.length(); i++){
				JSONObject c = contacts.getJSONObject(i);
				// Storing each json item in variable				
				String name = c.getString(TAG_NAME);
				String ipp = c.getString(TAG_IPP);
				String birth = c.getString(TAG_BIRTH);
				String sex = c.getString(TAG_SEX);
				
				// creating new HashMap
				HashMap<String, String> map = new HashMap<String, String>();
				
				
				// adding each child node to HashMap key => value
					map.put(TAG_NAME, name);
					map.put(TAG_IPP, ipp);
					map.put(TAG_BIRTH, birth);
					map.put(TAG_SEX, sex);					
					contactList.add(map);
						
			}			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	
		/**
		 * Updating parsed JSON data into ListView
		 * */
		ListAdapter adapter = new SimpleAdapter(
				this, 
				contactList,
				R.layout.list_item,
				new String[] { TAG_NAME, TAG_IPP, TAG_BIRTH, TAG_SEX }, new int[] {
				R.id.name, R.id.ipp, R.id.birth, R.id.sex}
				);
		
       
		setListAdapter(adapter); 
		
		// selecting single ListView item && enable the fast scroll view
		ListView lv = getListView();
		lv.setFastScrollEnabled(true);   
		
		// Launching new screen on Selecting Single ListItem     
		lv.setOnItemClickListener(new OnItemClickListener() {   
			
			 
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// getting values from selected ListItem
				traitementDesDonnees();
				String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
				String ipp = ((TextView) view.findViewById(R.id.ipp)).getText().toString();  
				String birth = ((TextView) view.findViewById(R.id.birth)).getText().toString();
				String sex = ((TextView) view.findViewById(R.id.sex)).getText().toString();
				
				// Starting new intent
				
				Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
				in.putExtra(TAG_NAME, name);
				in.putExtra(TAG_IPP, ipp);
				in.putExtra(TAG_BIRTH, birth);
				in.putExtra(TAG_SEX, sex);
				startActivity(in);
				
			}
		});
		
		

	}

}
0
scinarf Messages postés 1119 Date d'inscription samedi 18 novembre 2006 Statut Membre Dernière intervention 25 septembre 2014 252
Modifié par scinarf le 21/02/2013 à 16:27
Je ne vois pas de "onResume()" c'est volontaire ?

Lorsque des intent sont utilisés il faut faire ajouté une ligne avec les autres class extend activity dans le androidManifest voir lien ci-dessous:
https://forums.commentcamarche.net/forum/affich-26784030-intent-android

les logs suivant renvoient ils la valeur souhaitée dans le Logcat ?

Log.d("alerte", jour);
Log.d("alerte", mois);
Log.d("alerte", annee);
Log.d("alerte", patient);
Log.d("alerte", bouton);


Je regarde le code plus précisement ...
0
scinarf Messages postés 1119 Date d'inscription samedi 18 novembre 2006 Statut Membre Dernière intervention 25 septembre 2014 252
21 févr. 2013 à 16:40
D'après le Log l'erreur provient de la fonction send

private void send(String jour, String mois, String annee, String patient, String bouton){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("jour",jour));
nameValuePairs.add(new BasicNameValuePair("mois",mois));
nameValuePairs.add(new BasicNameValuePair("annee",annee));
nameValuePairs.add(new BasicNameValuePair("patient",patient));
nameValuePairs.add(new BasicNameValuePair("bouton",bouton));

try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.18.55.82/Android/patient.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();

}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}

Sur quel APi tu developpes ?

Regarde ce lien, peut etre trouveras tu des choses utiles : https://stackoverflow.com/questions/4457492/how-do-i-use-the-simple-http-client-in-android
0
sur l'API 15
0