Bonjour,
Je récupère des donnnées Json grâce à la classe JsonParser ...
... dans mon Asyntask
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 public class JSONParser { public static JSONObject getJSONFromPost(String url) throws MalformedURLException, IOException, JSONException, ClientProtocolException, IllegalStateException { HttpGet httpPost = new HttpGet(url); return getJSONFrom(httpPost); } public static JSONObject getJSONFrom(HttpUriRequest req) throws ClientProtocolException, IOException, JSONException, IllegalStateException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(req); if (httpResponse.getStatusLine().getStatusCode()>=400) throw new IOException(httpResponse.getStatusLine().getReasonPhrase()); HttpEntity httpEntity = httpResponse.getEntity(); String jsonStr = EntityUtils.toString(httpEntity); return new JSONObject(jsonStr); } }
Ma question est la suivante pourquoi quand j’exécute le code suivante pour fermer correctement mon asynctask:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 private class MyTask extends AsyncTask<Void, Void, ArrayList<Video>> { private String URL_task = ""; private JSONObject json = null; private String error = null; private boolean isRunnig = true; @Override protected ArrayList<Video> doInBackground(Void ...unused) { while (isRunnig) { URL_task = PATH_TO_SCRIPT; try { json = JSONParser.getJSONFromPost(URL_task); JSONArray earthquakes = json.getJSONArray("videos"); nb_articles = earthquakes.length(); for (int i = 0; i < earthquakes.length(); i++) { JSONObject e = earthquakes.getJSONObject(i); Video video = new Video(e.getString("id_video")); listVideos.add(video); } } catch (Exception ex) { error = "Couldn't retrive data !"; Log.e("Json", error, ex); } isRunnig = false; if (isCancelled()) { Log.e("asyntask", "isCancelled()"); break; } } return listVideos; } protected void onPostExecute(ArrayList<Video> result) { mTask = null; if(error != null) Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show(); else { // TRAITEMENT NORMAL DE MA LISTE } } // onPostExecute(); @Override public void onCancelled () { isRunnig = false; } }
(où mTask est de type MyTask ) dans mon onDestroy() / onPause() ma requête HTTP continue de tourner. J'ai vue qu'il fallait utiliser un "abort" mais je ne vois pas l'utiliser dans mon cas. Merci d'avance pour votre aide.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3 if (mTask != null) mTask.cancel(true);
Partager