IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Composants graphiques Android Discussion :

Comment mettre à jour un ListView depuis un Asyntask


Sujet :

Composants graphiques Android

  1. #1
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut Comment mettre à jour un ListView depuis un Asyntask
    Bonjour,
    Je veux mettre à jour mon ArrayList à partir des données récupérées d'un serveur .J'ai passé des heures de recherche mais je n'arrives pas intégrer l'actualisation de mon ArrayList dans le bloc Asyntask.
    Aidez moi s'il vous plait et merci d'avance.
    Voila mon classe java:
    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
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    package com.example.projet_fin_etude;
     
     
     
     
     
    import java.util.ArrayList;
     
    import java.util.Collections;
     
     
    import java.util.HashMap;
     
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
     
    import android.app.ListActivity;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    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.Toast;
     
    public class Trie  extends ListActivity {
    	ArrayList <Place> myList =new ArrayList <Place>();
     
    	private static final String TAG_rows = "rows";
    	private static final String TAG_elements = "elements";
     
    	private static final String TAG_distance= "distance";
    	private static final String TAG_value= "value";
     
    	String url;
     
    	ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
     
    	@SuppressWarnings("unchecked")
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.listplaceholder);
     
     
    		Intent intent = getIntent();
    		Bundle extras =intent.getExtras();
    		if (extras != null){
    			this.myList = (ArrayList<Place>) extras.getSerializable("myList");
    			double lt=Double.parseDouble(intent.getStringExtra("latitude"));
    			double lg=Double.parseDouble(intent.getStringExtra("longitude"));
    			 url="https://maps.googleapis.com/maps/api/distancematrix/json?origins="+lt+","+lg+"&destinations=";
    			 int i;
    			for( i=0;i<(myList.size())-1;i++)
    			{
    			url=url+myList.get(i).getLatitude()+","+myList.get(i).getLongitude()+"%7C";	
    			}
     
    			url=url+myList.get(i).getLatitude()+","+myList.get(i).getLongitude()+"&mode=walking&language=fr-FR&sensor=true";
    			 Log.d("test", url);
     
    			new AsyncTask<Void, Void, JSONObject>(){
    				@Override
    				protected JSONObject doInBackground(Void... params) {
    						// instancier la classe JsonParser
    						JsonParser jParser = new JsonParser ();
    						// récupérer le JSONObject à partir de l’url du fichier employes.json
    						JSONObject json = jParser.getJSONFromUrl(url);
     
    						return json;
    					};
     
    					protected void onPostExecute(JSONObject json) {
     
    						try {
     
     
    							// récupérer le tableau lignes
    							JSONArray lignes = json.getJSONArray(TAG_rows);
    							// récupérer le tableau elements
    							JSONObject elements = lignes.getJSONObject(0);
    							JSONArray results = elements.getJSONArray(TAG_elements);
    							// parcourir toute la liste des employés
    							for(int i = 0; i < results.length(); i++){
    					 			// récupérer un element de type JSONObject
    								JSONObject el = results.getJSONObject(i);
    								// récupérer le JSONObject Distance qui contient deux items
    								JSONObject dist = el.getJSONObject(TAG_distance);
    								String value = dist.getString(TAG_value);
    								Log.d("value", value);
    								int val_dist=Integer.parseInt(value);
     
    								Place p = new Place(myList.get(i).getReference(),myList.get(i).getNom(),myList.get(i).getAdresse(),myList.get(i).getLatitude(),myList.get(i).getLongitude(),val_dist); 
    								myList.set(i,p);
     
     
    							}
    							Collections.sort(myList, Place.DST_COMPARATOR);
    							for(int i=0;i<myList.size();i++)
    							{
    							Log.d("objet",myList.get(i).toString());
    							}
     
     
     
     
     
    			}
     
    						catch(JSONException e)
    						{
    							e.printStackTrace();
    						}
    					};
     
     
    				}.execute();
    			}
     
     
    	for(int i=0;i<myList.size();i++)
    	{
    		HashMap<String, String> map = new HashMap<String, String>();
    		map.put("id",  String.valueOf(i));
    		map.put("name",myList.get(i).getNom());
    		map.put("adresse", myList.get(i).getAdresse());
    		list.add(map);
    	}
    	  ListAdapter adapter = new SimpleAdapter(this, list , R.layout.activity_trie, 
                  new String[] { "name", "adresse" }, 
                  new int[] { R.id.item_title, R.id.item_subtitle });
    	  setListAdapter(adapter);
    	  final ListView lv = getListView();
    	  lv.setTextFilterEnabled(true);	
    	  lv.setOnItemClickListener(new OnItemClickListener() {
    	  	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {        		
    	  		HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);	        		
    	  		Toast.makeText(Trie.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 
     
     
    	  }
    	  });
     
    	  }
     
     
     
     
     
     
     
     
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.activity_trie, menu);
    		return true;
    	}
     
    }
    Les fichiers xml:
    activity_trie.xml

    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
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
         android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="7dp"
        tools:context=".Trie" >
    <TextView  
    	android:id="@+id/item_title"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:padding="2dp"
        android:textSize="20dp" />
        <TextView  
    	android:id="@+id/item_subtitle"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:padding="2dp"
        android:textSize="13dp" />
     
    </LinearLayout>

    listplaceholder.xml
    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
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
         >
     
        <ListView
    	 	android:id="@id/android:list"
    	    android:layout_width="fill_parent"
    	    android:layout_height="wrap_content"
    	    android:layout_weight="1"
    	 	android:drawSelectorOnTop="false" />
     
        <TextView
            android:id="@id/android:empty"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="No data"/> 
     
    </LinearLayout>

  2. #2
    Membre actif
    Inscrit en
    Décembre 2008
    Messages
    280
    Détails du profil
    Informations forums :
    Inscription : Décembre 2008
    Messages : 280
    Points : 261
    Points
    261
    Par défaut
    Salut,
    Dans le psot execute une fois que ta liste est à jour, tu fais un
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    adapter.NotifyDataSetChanged();
    Paye Tes Dettes - Applciation android.

    DevHackSecure - Pense bête d'un étudiant en informatique - Tutos DEV

    " I also realize that _everybody_ thinks that they are right, and that they are supported by all other right-thinking people. That's just how people work. We all think we're better than average." Linus Torvalds

  3. #3
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    Merci pour votre réponse mais ça ne marche pas.

  4. #4
    Rédacteur
    Avatar de David55
    Homme Profil pro
    Ingénieur informatique
    Inscrit en
    Août 2010
    Messages
    1 542
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 1 542
    Points : 2 808
    Points
    2 808
    Par défaut
    Tu peux toujours essayer de redéfinir ton adapter:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    adapter = new Adapter(...);
    lv.setAdapter(adapter)
    ;

  5. #5
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    Merci pour votre réponse mais encore ça ne marche pas .
    Mon problème est au niveau de ces instructions qui sont marquées en rouge dés que j'essaie d'ajouter la mise à jour de la listview dans la méthode onPosteExcute:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    ListAdapter adapter = new SimpleAdapter(this, list , R.layout.activity_trie, 
    						              new String[] { "name", "adresse" }, 
    						              new int[] { R.id.item_title, R.id.item_subtitle });

  6. #6
    Rédacteur
    Avatar de David55
    Homme Profil pro
    Ingénieur informatique
    Inscrit en
    Août 2010
    Messages
    1 542
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 1 542
    Points : 2 808
    Points
    2 808
    Par défaut
    Les deux chaines de caractère ne s'affiche pas?
    As tu bien ajouté l'adapter à ta ListView?

  7. #7
    Membre éprouvé
    Profil pro
    Inscrit en
    Janvier 2011
    Messages
    757
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2011
    Messages : 757
    Points : 968
    Points
    968
    Par défaut
    Peux tu nous dire le message d'erreur donné par Eclipse ?

    Je pense tout de même savoir d'où ça vient :
    Le this utilisé dans ton new SimpleAdapter(...) ne fait pas référence à un Context mais à ton AsyncTask.
    Pour résoudre cela, tu peux écrire ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    ListAdapter adapter = new SimpleAdapter(Trie.this, list , R.layout.activity_trie, 
    						              new String[] { "name", "adresse" }, 
    						              new int[] { R.id.item_title, R.id.item_subtitle });
    Ou alors, enregistrer le Context de ton Activity à la création de ton AsyncTask.

  8. #8
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    Merci pour tous vos réponses.
    Je suis débutante et je ne comprends pas bien l'utilisation des listview .
    Voici mon code :
    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
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    package com.example.projet_fin_etude;
     
     
     
     
     
    import java.util.ArrayList;
     
    import java.util.Collections;
     
     
    import java.util.HashMap;
     
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
     
    import android.app.ListActivity;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    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.Toast;
     
    public class Trie  extends ListActivity {
    	ArrayList <Place> myList =new ArrayList <Place>();
     
    	private static final String TAG_rows = "rows";
    	private static final String TAG_elements = "elements";
     
    	private static final String TAG_distance= "distance";
    	private static final String TAG_value= "value";
     
    	String url;
     
    	ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
     
    	@SuppressWarnings("unchecked")
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.listplaceholder);
     
     
    		Intent intent = getIntent();
    		Bundle extras =intent.getExtras();
    		if (extras != null){
    			this.myList = (ArrayList<Place>) extras.getSerializable("myList");
    			double lt=Double.parseDouble(intent.getStringExtra("latitude"));
    			double lg=Double.parseDouble(intent.getStringExtra("longitude"));
    			 url="https://maps.googleapis.com/maps/api/distancematrix/json?origins="+lt+","+lg+"&destinations=";
    			 int i;
    			for( i=0;i<(myList.size())-1;i++)
    			{
    			url=url+myList.get(i).getLatitude()+","+myList.get(i).getLongitude()+"%7C";	
    			}
     
    			url=url+myList.get(i).getLatitude()+","+myList.get(i).getLongitude()+"&mode=walking&language=fr-FR&sensor=true";
    			 Log.d("test", url);
     
    			new AsyncTask<Void, Void, JSONObject>(){
    				@Override
    				protected JSONObject doInBackground(Void... params) {
    						// instancier la classe JsonParser
    						JsonParser jParser = new JsonParser ();
    						// récupérer le JSONObject à partir de l’url du fichier employes.json
    						JSONObject json = jParser.getJSONFromUrl(url);
     
    						return json;
    					};
     
    					protected void onPostExecute(JSONObject json) {
     
    						try {
     
     
    							// récupérer le tableau lignes
    							JSONArray lignes = json.getJSONArray(TAG_rows);
    							// récupérer le tableau elements
    							JSONObject elements = lignes.getJSONObject(0);
    							JSONArray results = elements.getJSONArray(TAG_elements);
    							// parcourir toute la liste des employés
    							for(int i = 0; i < results.length(); i++){
    					 			// récupérer un element de type JSONObject
    								JSONObject el = results.getJSONObject(i);
    								// récupérer le JSONObject Distance qui contient deux items
    								JSONObject dist = el.getJSONObject(TAG_distance);
    								String value = dist.getString(TAG_value);
    								Log.d("value", value);
    								int val_dist=Integer.parseInt(value);
     
    								Place p = new Place(myList.get(i).getReference(),myList.get(i).getNom(),myList.get(i).getAdresse(),myList.get(i).getLatitude(),myList.get(i).getLongitude(),val_dist); 
    								myList.set(i,p);
     
     
    							}
    							Collections.sort(myList, Place.DST_COMPARATOR);
    							for(int i=0;i<myList.size();i++)
    							{
    							Log.d("objet",myList.get(i).toString());
    							}
    							for(int i=0;i<myList.size();i++)
    							{
    								HashMap<String, String> map = new HashMap<String, String>();
    								map.put("id",  String.valueOf(i));
    								map.put("name",myList.get(i).getNom());
    								map.put("adresse", myList.get(i).getAdresse());
    								list.add(map);
    							}
    							  ListAdapter adapter = new SimpleAdapter(this, list , R.layout.activity_trie, 
    						              new String[] { "name", "adresse" }, 
    						              new int[] { R.id.item_title, R.id.item_subtitle });
    							  setListAdapter(adapter);
    							  final ListView lv = getListView();
    							  lv.setTextFilterEnabled(true);	
    							  lv.setOnItemClickListener(new OnItemClickListener() {
    							  	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {        		
    							  		HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);	        		
    							  		Toast.makeText(Trie.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 
     
     
    							  }
    							  });
     
     
     
     
    			}
     
    						catch(JSONException e)
    						{
    							e.printStackTrace();
    						}
    					};
     
     
    				}.execute();
    			}
    L'erreur d'eclipse est
    The constructor SimpleAdapter(new AsyncTask<Void,Void,JSONObject>(){}, ArrayList<HashMap<String,String>>, int, String[], int[]) is undefined

  9. #9
    Rédacteur
    Avatar de David55
    Homme Profil pro
    Ingénieur informatique
    Inscrit en
    Août 2010
    Messages
    1 542
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 1 542
    Points : 2 808
    Points
    2 808
    Par défaut
    As tu essayé la solution de Simon : http://www.developpez.net/forums/d13...k/#post7253319

  10. #10
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    J'ai essayé , ça me résout le problème d'eclipse mais dans l'exécution la listView ne se met pas à jour .

  11. #11
    Membre du Club
    Femme Profil pro
    Etudiante
    Inscrit en
    Février 2013
    Messages
    95
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Etudiante
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Février 2013
    Messages : 95
    Points : 68
    Points
    68
    Par défaut
    Merci pour tous ça marche bien maintenant

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 2
    Dernier message: 31/01/2012, 10h05
  2. Réponses: 1
    Dernier message: 15/09/2006, 11h24
  3. Réponses: 2
    Dernier message: 31/08/2006, 09h56
  4. Comment mettre à jour une ligne sans doublon via déclencheur
    Par fuelcontact dans le forum MS SQL Server
    Réponses: 2
    Dernier message: 02/08/2004, 15h56
  5. Mettre à jour une table depuis une autre
    Par rsc dans le forum SQL
    Réponses: 4
    Dernier message: 09/07/2004, 10h08

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo