Précédent   Forum du club des développeurs et IT Pro > Java > Général Java > Java & Mobiles > Android
Android Forum d'entraide sur Android, la plateforme mobile de Google pour téléphones portables et Smartphones. Avant de poster -> FAQ Android
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse
 
Outils de la discussion
Publicité
'
Vieux 08/01/2013, 11h33   #1
zerkos
Membre du Club
 
Homme zakaria
Développeur informatique
Inscription : octobre 2010
Messages : 141
Détails du profil
Informations personnelles :
Nom : Homme zakaria
Localisation : Maroc

Informations professionnelles :
Activité : Développeur informatique

Informations forums :
Inscription : octobre 2010
Messages : 141
Points : 51
Points : 51
Par défaut the application has stopped unexpectedly

Bonjour,

Je ne sais pas pour quoi ce message est toujours s'affiche
tous les tutoriel du parsing qui j'ai essaie quand je met mon URL et mes tag
j’exécute rien que ce message erreur s'affiche,

C'est plus de 3 jours que j'essaie presq tout les tuto > "du remplir un listview a partir d'un fichier xml", et je n'arrive pas, toujours le même message

the application MyApp has stopped unexpectedly
please try again
zerkos est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 11h48   #2
Mygale1978
Expert Confirmé Sénior
 
Homme Laurent Willems
Expert Stop/Start
Inscription : septembre 2002
Messages : 2 882
Détails du profil
Informations personnelles :
Nom : Homme Laurent Willems
Âge : 34
Localisation : Belgique

Informations professionnelles :
Activité : Expert Stop/Start

Informations forums :
Inscription : septembre 2002
Messages : 2 882
Points : 5 412
Points : 5 412
Salut,

Sans plus de détail, il sera réellement difficile de t'aider.
__________________
Alea Jacta Test!
Mygale1978 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 12h01   #3
zerkos
Membre du Club
 
Homme zakaria
Développeur informatique
Inscription : octobre 2010
Messages : 141
Détails du profil
Informations personnelles :
Nom : Homme zakaria
Localisation : Maroc

Informations professionnelles :
Activité : Développeur informatique

Informations forums :
Inscription : octobre 2010
Messages : 141
Points : 51
Points : 51
salut,

mon problème ce que je veux remplir une listeview a partir d'un fichier xml, j'ai essaie beaucoup de tutoriel, ces tutorial ça marche avec les données qui contient au moment que je les modifies ça marche pas toujours le même message d'erreur, ce que je pense c'est un problème de temps de chargement de mon URL, si vous avez d'idée ou bien un autre tutoriel pour remplir listview a partir d'un XML

merci d'avance
zerkos est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 12h23   #4
Susp3nded
Nouveau Membre du Club
 
Femme
Ingénieur développement logiciels
Inscription : mai 2011
Messages : 22
Détails du profil
Informations personnelles :
Sexe : Femme

Informations professionnelles :
Activité : Ingénieur développement logiciels
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : mai 2011
Messages : 22
Points : 32
Points : 32
Salut

Pourrais-tu nous fournir la stacktrace? Un plantage aussi radical est souvent dû a une détise du genre NullPointerException (d'apres ma courte experience en Android)
Susp3nded est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 12h50   #5
zerkos
Membre du Club
 
Homme zakaria
Développeur informatique
Inscription : octobre 2010
Messages : 141
Détails du profil
Informations personnelles :
Nom : Homme zakaria
Localisation : Maroc

Informations professionnelles :
Activité : Développeur informatique

Informations forums :
Inscription : octobre 2010
Messages : 141
Points : 51
Points : 51
je suis désolé j'ai pas pu enregistré le log a partir d'ADT, pour cela j'ai fais une capture écran

log.png


merci pour votre aide
zerkos est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 13h31   #6
Susp3nded
Nouveau Membre du Club
 
Femme
Ingénieur développement logiciels
Inscription : mai 2011
Messages : 22
Détails du profil
Informations personnelles :
Sexe : Femme

Informations professionnelles :
Activité : Ingénieur développement logiciels
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : mai 2011
Messages : 22
Points : 32
Points : 32
Je veux bien la totalité du log, ou du moins la suite en bas.

Tu as un soucis de NullPointerException au chargement du fichier XML (vers la fin) qui est causé par.... je veux bien la suite
Susp3nded est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 13h32   #7
nicroman
Modérateur
 
Homme Nicolas Romantzoff
Ingénieur systèmes et réseaux
Inscription : février 2007
Messages : 2 862
Détails du profil
Informations personnelles :
Nom : Homme Nicolas Romantzoff
Localisation : France, Rhône (Rhône Alpes)

Informations professionnelles :
Activité : Ingénieur systèmes et réseaux
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : février 2007
Messages : 2 862
Points : 4 915
Points : 4 915
Envoyer un message via Skype™ à nicroman
Oui, c'est à la ligne 37 du fichier AndroidXMLParsingActivity.java, dans la fonction onCreate()... utilisation d'un objet null....

Sans plus de code, difficile de savoir ce qu'il s'y passe....


Pour le logcat un simple ctrl+c / ctrl+v suffit:
On click la première ligne...
On shfit-click la dernière ligne voulue...
Ctrl+c
Et ctrl+v entre des balises code ici:
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
01-08 12:32:17.913: D/ConnectivityService(97): ConnectivityChange for mobile: CONNECTED/CONNECTED
01-08 12:32:18.023: A/NetworkStats(97): problem reading network stats
01-08 12:32:18.023: A/NetworkStats(97): java.lang.IllegalStateException: problem parsing idx 1
01-08 12:32:18.023: A/NetworkStats(97): 	at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:300)
01-08 12:32:18.023: A/NetworkStats(97): 	at com.android.server.NetworkManagementService.getNetworkStatsUidDetail(NetworkManagementService.java:1282)
01-08 12:32:18.023: A/NetworkStats(97): 	at com.android.server.net.NetworkStatsService.performPollLocked(NetworkStatsService.java:831)
01-08 12:32:18.023: A/NetworkStats(97): 	at com.android.server.net.NetworkStatsService.updateIfacesLocked(NetworkStatsService.java:743)
01-08 12:32:18.023: A/NetworkStats(97): 	at com.android.server.net.NetworkStatsService.updateIfaces(NetworkStatsService.java:721)
01-08 12:32:18.023: A/NetworkStats(97): 	at com.android.server.net.NetworkStatsService.access$000(NetworkStatsService.java:128)
01-08 12:32:18.023: A/NetworkStats(97): 	at com.android.server.net.NetworkStatsService$1.onReceive(NetworkStatsService.java:612)
01-08 12:32:18.023: A/NetworkStats(97): 	at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)
01-08 12:32:18.023: A/NetworkStats(97): 	at android.os.Handler.handleCallback(Handler.java:605)
01-08 12:32:18.023: A/NetworkStats(97): 	at android.os.Handler.dispatchMessage(Handler.java:92)
01-08 12:32:18.023: A/NetworkStats(97): 	at android.os.Looper.loop(Looper.java:137)
01-08 12:32:18.023: A/NetworkStats(97): 	at android.os.HandlerThread.run(HandlerThread.java:60)
01-08 12:32:18.023: A/NetworkStats(97): Caused by: java.io.FileNotFoundException: /proc/net/xt_qtaguid/stats: open failed: ENOENT (No such file or directory)
01-08 12:32:18.023: A/NetworkStats(97): 	at libcore.io.IoBridge.open(IoBridge.java:406)
01-08 12:32:18.023: A/NetworkStats(97): 	at java.io.FileInputStream.<init>(FileInputStream.java:78)
01-08 12:32:18.023: A/NetworkStats(97): 	at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:269)
01-08 12:32:18.023: A/NetworkStats(97): 	... 11 more
01-08 12:32:18.023: A/NetworkStats(97): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
01-08 12:32:18.023: A/NetworkStats(97): 	at libcore.io.Posix.open(Native Method)
01-08 12:32:18.023: A/NetworkStats(97): 	at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
01-08 12:32:18.023: A/NetworkStats(97): 	at libcore.io.IoBridge.open(IoBridge.java:390)
01-08 12:32:18.023: A/NetworkStats(97): 	... 13 more
01-08 12:32:18.203: V/AlarmClock(409): AlarmInitReceiver finished
__________________
N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
Et surtout
nicroman est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 13h42   #8
zerkos
Membre du Club
 
Homme zakaria
Développeur informatique
Inscription : octobre 2010
Messages : 141
Détails du profil
Informations personnelles :
Nom : Homme zakaria
Localisation : Maroc

Informations professionnelles :
Activité : Développeur informatique

Informations forums :
Inscription : octobre 2010
Messages : 141
Points : 51
Points : 51
voila le code LOG
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
01-08 11:41:24.730: E/Error:(704): expected: /META read: HEAD (position:END_TAG </HEAD>@11:8 in java.io.StringReader@44ed2830) 
01-08 11:41:24.880: E/AndroidRuntime(704): FATAL EXCEPTION: main
01-08 11:41:24.880: E/AndroidRuntime(704): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.xmlparsing/com.androidhive.xmlparsing.AndroidXMLParsingActivity}: java.lang.NullPointerException
01-08 11:41:24.880: E/AndroidRuntime(704): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at android.os.Handler.dispatchMessage(Handler.java:99)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at android.os.Looper.loop(Looper.java:123)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at android.app.ActivityThread.main(ActivityThread.java:4627)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at java.lang.reflect.Method.invokeNative(Native Method)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at java.lang.reflect.Method.invoke(Method.java:521)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at dalvik.system.NativeStart.main(Native Method)
01-08 11:41:24.880: E/AndroidRuntime(704): Caused by: java.lang.NullPointerException
01-08 11:41:24.880: E/AndroidRuntime(704): 	at com.androidhive.xmlparsing.AndroidXMLParsingActivity.onCreate(AndroidXMLParsingActivity.java:37)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-08 11:41:24.880: E/AndroidRuntime(704): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-08 11:41:24.880: E/AndroidRuntime(704): 	... 11 more
mon code
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
 
public class AndroidXMLParsingActivity extends ListActivity {
 
	// All static variables
	static final String URL = "http://news.abidjan.net/apps/iphone/une.xml";
	// XML node keys
	static final String KEY_ITEM = "item"; // parent node
	static final String KEY_TITLE = "title";
	static final String KEY_AUTHOR = "author";
	static final String KEY_PUBDATE = "pubDate";
	static final String KEY_DESC = "description";
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
 
		XMLParser parser = new XMLParser();
		String xml = parser.getXmlFromUrl(URL); // getting XML
		Document doc = parser.getDomElement(xml); // getting DOM element
 
		NodeList nl = doc.getElementsByTagName(KEY_ITEM);
		// looping through all item nodes <item>
		for (int i = 0; i < nl.getLength(); i++) {
			// creating new HashMap
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element) nl.item(i);
			// adding each child node to HashMap key => value
			map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
			map.put(KEY_AUTHOR, parser.getValue(e, KEY_AUTHOR));
			map.put(KEY_PUBDATE, parser.getValue(e, KEY_PUBDATE));
 
			// adding HashList to ArrayList
			menuItems.add(map);
		}
 
		// Adding menuItems to ListView
		ListAdapter adapter = new SimpleAdapter(this, menuItems,
				R.layout.list_item,
				new String[] { KEY_AUTHOR, KEY_TITLE, KEY_PUBDATE }, new int[] {
						R.id.name, R.id.desciption, R.id.cost });
 
		setListAdapter(adapter);
 
//		// selecting single ListView item
//		ListView lv = getListView();
//
//		lv.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> parent, View view,
//					int position, long id) {
//				// getting values from selected ListItem
//				String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
//				String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
//				String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
//				
//				// Starting new intent
//				Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
//				in.putExtra(KEY_TITLE, name);
//				in.putExtra(KEY_PUBDATE, cost);
//				in.putExtra(KEY_TITLE, description);
//				startActivity(in);
//
//			}
//		});
	}
}
merci infiniment pour votre aide
zerkos est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 13h51   #9
wax78
Modérateur
 
Avatar de wax78
 
Homme Renaud Warnotte
Développeur informatique
Inscription : août 2006
Messages : 2 141
Détails du profil
Informations personnelles :
Nom : Homme Renaud Warnotte
Âge : 32
Localisation : Belgique

Informations professionnelles :
Activité : Développeur informatique
Secteur : High Tech - Éditeur de logiciels

Informations forums :
Inscription : août 2006
Messages : 2 141
Points : 4 091
Points : 4 091
Envoyer un message via MSN à wax78
Comme le dit le stacktrace :
Citation:
at com.androidhive.xmlparsing.AndroidXMLParsingActivity.onCreate
(AndroidXMLParsingActivity.java:37)
Le problème se situe à la ligne 37, donc il faut voir quelle est cette ligne pour bien faire car si je regarde le code ca correspond a la } (ce qui n'est surement pas la réalité).
wax78 est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 13h57   #10
nicroman
Modérateur
 
Homme Nicolas Romantzoff
Ingénieur systèmes et réseaux
Inscription : février 2007
Messages : 2 862
Détails du profil
Informations personnelles :
Nom : Homme Nicolas Romantzoff
Localisation : France, Rhône (Rhône Alpes)

Informations professionnelles :
Activité : Ingénieur systèmes et réseaux
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : février 2007
Messages : 2 862
Points : 4 915
Points : 4 915
Envoyer un message via Skype™ à nicroman
[Boule de cristal on]

Je pense que le problème se situe ici:
Code :
1
2
3
4
 
		String xml = parser.getXmlFromUrl(URL); // getting XML
		Document doc = parser.getDomElement(xml); // getting DOM element
                NodeList nl = doc.getElementsByTagName(KEY_ITEM);
1. C'est interdit... on ne récupère pas un truc d'internet dans le onCreate() (d'ailleurs on ne fait pas d'IO dans le onCreate du tout).

2. Je ne connais pas le code de XMLParser mais quelque chose me dit qu'il a été programmé au lance-pierres et (justement) ne lance aucune exception si quelque chose s'est mal passé (et pire, passe sous silence l'exception, qui doit être ici un "NetworkOnMainThreadException").
Du coup "String xml" est null....

3. Pareil pour "parser.getDomElement(xml);", qui au lieu d'indiquer une erreur de paramètre, renvoit null....

4. doc.getElementsByTagName foire alors avec un NullPointerException.

[Boule de cristal off]

On pourrait avoir le code de XMLParser ?
__________________
N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
Et surtout
nicroman est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 15h51   #11
zerkos
Membre du Club
 
Homme zakaria
Développeur informatique
Inscription : octobre 2010
Messages : 141
Détails du profil
Informations personnelles :
Nom : Homme zakaria
Localisation : Maroc

Informations professionnelles :
Activité : Développeur informatique

Informations forums :
Inscription : octobre 2010
Messages : 141
Points : 51
Points : 51
salut,

j suis désolé pour le retard

la ligne 37 :

Code :
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
le XMLParser
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
 
public class XMLParser {
 
	// constructor
	public XMLParser() {
 
	}
 
	/**
	 * Getting XML from URL making HTTP request
	 * @param url string
	 * */
	public String getXmlFromUrl(String url) {
		String xml = null;
 
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
 
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			xml = EntityUtils.toString(httpEntity);
 
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// return XML
		return xml;
	}
 
	/**
	 * Getting XML DOM element
	 * @param XML string
	 * */
	public Document getDomElement(String xml){
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
 
			DocumentBuilder db = dbf.newDocumentBuilder();
 
			InputSource is = new InputSource();
		        is.setCharacterStream(new StringReader(xml));
		        doc = db.parse(is); 
 
			} catch (ParserConfigurationException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			} catch (SAXException e) {
				Log.e("Error: ", e.getMessage());
	            return null;
			} catch (IOException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			}
 
	        return doc;
	}
 
	/** Getting node value
	  * @param elem element
	  */
	 public final String getElementValue( Node elem ) {
	     Node child;
	     if( elem != null){
	         if (elem.hasChildNodes()){
	             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
	                 if( child.getNodeType() == Node.TEXT_NODE  ){
	                     return child.getNodeValue();
	                 }
	             }
	         }
	     }
	     return "";
	 }
 
	 /**
	  * Getting node value
	  * @param Element node
	  * @param key string
	  * */
	 public String getValue(Element item, String str) {		
			NodeList n = item.getElementsByTagName(str);		
			return this.getElementValue(n.item(0));
		}
}
@nicroman : le script je l'ai telechargé et je l'ai tésté , il est fonctionnel mais quand j'ai change le URL et les tages ne marche plus
zerkos est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 16h03   #12
zerkos
Membre du Club
 
Homme zakaria
Développeur informatique
Inscription : octobre 2010
Messages : 141
Détails du profil
Informations personnelles :
Nom : Homme zakaria
Localisation : Maroc

Informations professionnelles :
Activité : Développeur informatique

Informations forums :
Inscription : octobre 2010
Messages : 141
Points : 51
Points : 51
est ce que la structure du fichier XML peux être la cause ??

dans mon script je précise node parent "item" et mon fichier XML a la structure suivant
Code :
1
2
3
4
5
6
7
8
9
10
 
<channel>
  <title></title>
  ...
  <item>
    <title></title>
    <photo></photo>
     ...
  </item>
</channel>
Code :
1
2
3
 
static final String KEY_ITEM = "item"; // parent node
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
zerkos est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 16h22   #13
nicroman
Modérateur
 
Homme Nicolas Romantzoff
Ingénieur systèmes et réseaux
Inscription : février 2007
Messages : 2 862
Détails du profil
Informations personnelles :
Nom : Homme Nicolas Romantzoff
Localisation : France, Rhône (Rhône Alpes)

Informations professionnelles :
Activité : Ingénieur systèmes et réseaux
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : février 2007
Messages : 2 862
Points : 4 915
Points : 4 915
Envoyer un message via Skype™ à nicroman
Relis attentivement mon message... j'ai donné exactement (merci la boule de cristal) toute l'explication et même les raisons !!!

Si ca plante sur
Code :
1
2
 
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
C'est que "doc" est null
Si "doc" est null c'est parceque "xml" est null.
Si "xml" est null c'ets parceque la fonction getXmlFromUrl() ne renvoit aucune exception (juste un string null si quelque chose s'est mal passé).
getXmlFromUrl() ne lance aucune exception parcequ'il a été programmé à coup de lance-pierres (voir mes commentaires):
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 
public String getXmlFromUrl(String url) {
		String xml = null; // <= inutile ou on renvoit le XML, ou on a lancé une exception (pas de return)
 
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
                        // UN POST SANS DONNEES ? bizarre bizarre
			HttpPost httpPost = new HttpPost(url);
 
			HttpResponse httpResponse = httpClient.execute(httpPost);
                        // Et si la réponse est une erreur ? genre 404, 500 ???
                        // Bien tester getStatusLine() avant de faire appel à l'entity
			HttpEntity httpEntity = httpResponse.getEntity();
                        // ok                        
			xml = EntityUtils.toString(httpEntity);
 
		} catch (UnsupportedEncodingException e) {
                        // PAS BON !!! Il faut signaler à l'appelant que la réponse est indechiffrable (lancer un IllegalStateException par exemple) ! (et utiliser Log.e(xxx,xxxxxx,e); au lieu de e.printStackTrace(); )
			e.printStackTrace();
		} catch (ClientProtocolException e) {
                        // PAS BON !!! Il faut signaler à l'appelant que son URL est mauvaise ! (et utiliser Log.e(xxx,xxxxxx,e); au lieu de e.printStackTrace(); )
			e.printStackTrace();
		} catch (IOException e) {
                        // PAS BON !!! Il faut signaler à l'appelant que le service n'a pas pu répondre (donc en fait ne pas catcher IOException)
			e.printStackTrace();
		}
		// return XML
		return xml;
	}
à remplacer par un truc genre:
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
        public String getXmlFromUrl(String url) throws ClientProtocolException, IOException {
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);
			HttpResponse httpResponse = httpClient.execute(httpPost);
                        if (httpResponse.getStatusLine().getStatusCode()>=400)
                             throw new IOException(httpResponse.getStatusLine().getReasonPhrase());
			HttpEntity httpEntity = httpResponse.getEntity();
			return EntityUtils.toString(httpEntity);
		} catch (UnsupportedEncodingException e) {
                        throw new IllegalStateException("Response encoding not supported",e);
		}
	}

Par contre, je me suis gourré sur le NetworkOnMainThreadException, ce qui veut dire que le programme est pour Android 2.x-, et crachera avec Android 3.0+.

A noter que les mêmes remarques s'appliquent pour la fonction suivante:
Code :
1
2
3
4
 
} catch (ParserConfigurationException e) {
				Log.e("Error: ", e.getMessage());
				return null;
Ou on teste "null" apres l'appel de la fonction, ou la fonction ne renvoit jamais null.
Dans les deux cas, le "Log" n'est pas appelé correctement. Ce devrait être:
Code :
1
2
3
4
5
 
} catch (ParserConfigurationException e) {
				Log.e("XMLParser","Configuration Erro", e);
				return null;
}
__________________
N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
Et surtout
nicroman est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 16h54   #14
zerkos
Membre du Club
 
Homme zakaria
Développeur informatique
Inscription : octobre 2010
Messages : 141
Détails du profil
Informations personnelles :
Nom : Homme zakaria
Localisation : Maroc

Informations professionnelles :
Activité : Développeur informatique

Informations forums :
Inscription : octobre 2010
Messages : 141
Points : 51
Points : 51
merci nicroman

catch n'as pas été accepté
Code :
1
2
3
4
} catch (ParserConfigurationException e) {
				Log.e("XMLParser","Configuration Erro", e);
				return null;
}
le message d'erreur
Code :
Unreachable catch block for ParserConfigurationException. It is already handled by the catch block for ParserConfigurationException
zerkos est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 17h09   #15
nicroman
Modérateur
 
Homme Nicolas Romantzoff
Ingénieur systèmes et réseaux
Inscription : février 2007
Messages : 2 862
Détails du profil
Informations personnelles :
Nom : Homme Nicolas Romantzoff
Localisation : France, Rhône (Rhône Alpes)

Informations professionnelles :
Activité : Ingénieur systèmes et réseaux
Secteur : High Tech - Multimédia et Internet

Informations forums :
Inscription : février 2007
Messages : 2 862
Points : 4 915
Points : 4 915
Envoyer un message via Skype™ à nicroman
Citation:
Envoyé par zerkos Voir le message
Unreachable catch block for ParserConfigurationException. It is already handled by the catch block for ParserConfigurationException
Parceque le catch y est 2x
__________________
N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
Et surtout
nicroman est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 08/01/2013, 17h35   #16
zerkos
Membre du Club
 
Homme zakaria
Développeur informatique
Inscription : octobre 2010
Messages : 141
Détails du profil
Informations personnelles :
Nom : Homme zakaria
Localisation : Maroc

Informations professionnelles :
Activité : Développeur informatique

Informations forums :
Inscription : octobre 2010
Messages : 141
Points : 51
Points : 51
merci nicroman pour votre effort, j'ai mit votre code, mais ça n'as pas marché

j'ai changé:

Code :
1
2
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet); // httpPost
et j'ai enlevé les 2 catch

Code :
catch (ParserConfigurationException e) {...
zerkos est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse
Outils de la discussion

Navigation rapide


Fuseau horaire GMT +2. Il est actuellement 12h55.


 
 
 
 
Partenaires

Hébergement Web