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 :

Ajouter items dynamiquement à une ListView


Sujet :

Composants graphiques Android

  1. #1
    Membre habitué
    Homme Profil pro
    Inscrit en
    Octobre 2011
    Messages
    281
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 281
    Points : 161
    Points
    161
    Par défaut Ajouter items dynamiquement à une ListView
    Bonjour,

    Je récupère des articles de mon site Web que je récupère grâce à Json et que je met dans une ListView avec un Adapter personnalisé. Par défaut j'affiche les 5 premiers articles. J'aimerais que lorsque l'on arrive à la fin de la ListView donc à la fin du dernière article, 5 nouveaux items apparaissent dynamiquement. J'ai trouvé un exemple sur Internet (voir code) mais je n'arrive pas à le mettre en place dans mon cas. Pourriez-vous m'aider ? Merci.


    Mon Activité :

    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
    package com.applicazione;
     
     
    import java.util.ArrayList;
    import java.util.HashMap;
     
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
     
    import com.applicazione.R;
     
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.Window;
    import android.widget.AdapterView;
    import android.widget.ListView;
    import android.widget.AdapterView.OnItemClickListener;
     
    public class Bastia1905Activity extends Activity {
        /** Called when the activity is first created. */
     
        private myBaseAdapter adapter = null;
        private ListView lv;
        int itemPerPage = 5;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.attualita);
     
     
            ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
     
     
            JSONObject json = JSONfunctions.getJSONfromURL("http://bastia1905.com/android/export_android.php?nb_article="+itemPerPage);
     
            try{
     
            	JSONArray  earthquakes = json.getJSONArray("articles");
     
    	        for(int i=0;i<earthquakes.length();i++){						
    				HashMap<String, String> map = new HashMap<String, String>();	
    				JSONObject e = earthquakes.getJSONObject(i);
     
    				map.put("id",  String.valueOf(i));
    	        	map.put("titre", e.getString("titre"));
    	        	map.put("extrait", e.getString("extrait"));
    	        	map.put("thumb", e.getString("thumb"));
    	        	map.put("date", e.getString("date"));
    	        	map.put("img_article", e.getString("img_article"));
    	        	map.put("detail", e.getString("detail"));
    	        	mylist.add(map);			
    			}		
            }catch(JSONException e)        {
            	 Log.e("log_tag", "Error parsing data "+e.toString());
            }
     
     
            adapter = new myBaseAdapter(this,this,mylist);
            lv = (ListView)findViewById(R.id.list);
            lv.setAdapter(adapter);	
            lv.setTextFilterEnabled(true);
            lv.setOnItemClickListener(new OnItemClickListener() {
            	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {        		
            		@SuppressWarnings("unchecked")
    				HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);	        		
            		// Nous définissons notre intent en lui disant quelle classe il faut utiliser
    				Intent affichearticle = new Intent(getApplicationContext(),ArticleActivity.class);
    				affichearticle.putExtra("titre", o.get("titre"));
    				affichearticle.putExtra("detail", o.get("detail"));
    				affichearticle.putExtra("img_article", o.get("img_article"));
    				// On appelle l'activity
    				startActivity(affichearticle);
    			}
    		});
     
        }
     
     
     
    }

    Exemple de ListView avec chargement dynamique

    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
    package com.never;
     
    import java.util.ArrayList;
    import java.util.Calendar;
     
    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.AbsListView;
    import android.widget.AbsListView.OnScrollListener;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
     
     
    public class NeverEndingActivity extends Activity {
     
    	//how many to load on reaching the bottom
    	int itemsPerPage = 5;
    	boolean loadingMore = false;
     
     
     
     
    	ArrayList<String> myListItems;
    	ArrayAdapter<String> adapter;
     
    	//For test data :-)
    	Calendar d = Calendar.getInstance();
     
     
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {    	
            super.onCreate(savedInstanceState);
            setContentView(R.layout.listplaceholder);
     
     
    		//This will hold the new items
            myListItems = new ArrayList<String>();
            adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myListItems);
     
            ListView list = (ListView)findViewById(R.id.list);
     
     
    		//add the footer before adding the adapter, else the footer will nod load!
    		View footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
    		list.addFooterView(footerView);
     
    		//Set the adapter
    		list.setAdapter(adapter);
     
     
    		//Here is where the magic happens
    		list.setOnScrollListener(new OnScrollListener(){
     
    			//useless here, skip!
    			public void onScrollStateChanged(AbsListView view, int scrollState) {}
     
    			//dumdumdum			
    			public void onScroll(AbsListView view, int firstVisibleItem,
    					int visibleItemCount, int totalItemCount) {
     
     
    				//what is the bottom iten that is visible
    				int lastInScreen = firstVisibleItem + visibleItemCount;				
     
    				//is the bottom item visible & not loading more already ? Load more !
    				if((lastInScreen == totalItemCount) && !(loadingMore)){					
    					Thread thread =  new Thread(null, loadMoreListItems);
    			        thread.start();
    				}
    			}
    		});
     
     
    		//Load the first 15 items
    		Thread thread =  new Thread(null, loadMoreListItems);
            thread.start();
     
        }
     
     
        //Runnable to load the items 
        private Runnable loadMoreListItems = new Runnable() {			
    		public void run() {
    			//Set flag so we cant load new items 2 at the same time
    			loadingMore = true;
     
    			//Reset the array that holds the new items
    	    	myListItems = new ArrayList<String>();
     
    			//Simulate a delay, delete this on a production environment!
    	    	try { Thread.sleep(1000);
    			} catch (InterruptedException e) {}
     
    			//Get 15 new listitems
    	    	for (int i = 0; i < itemsPerPage; i++) {		
     
    				//Fill the item with some bogus information
    	        	myListItems.add("Date: " + (d.get(Calendar.MONTH)+ 1) + "/" + d.get(Calendar.DATE) + "/" + d.get(Calendar.YEAR) );          	
     
    				// +1 day :-D
    	        	d.add(Calendar.DATE, 1);
     
    			}
     
    			//Done! now continue on the UI thread
    	        runOnUiThread(returnRes);
     
    		}
    	};	
     
     
    	//Since we cant update our UI from a thread this Runnable takes care of that! 
        private Runnable returnRes = new Runnable() {
            public void run() {
     
    			//Loop thru the new items and add them to the adapter
    			if(myListItems != null && myListItems.size() > 0){
                    for(int i=0;i<myListItems.size();i++)
                    	adapter.add(myListItems.get(i));
                }
    ;
     
    			//Tell to the adapter that changes have been made, this will cause the list to refresh
                adapter.notifyDataSetChanged();
     
    			//Done loading more.
                loadingMore = false;
            }
        };
    }

  2. #2
    Membre extrêmement actif
    Avatar de Ryu2000
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2008
    Messages
    9 820
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Décembre 2008
    Messages : 9 820
    Points : 18 740
    Points
    18 740
    Par défaut
    C'est une mauvaise idée.

    Ici à chaque fois que l'utilisateur voudra voir cette liste, il devra tout télécharger.
    Il ni y aura pas accès en hors ligne.

    Tu devrais ajouter les articles dans ta base de données SQLite local et tu pourrais créer une ListView avec tout les articles à l'intérieur.

  3. #3
    Membre habitué
    Homme Profil pro
    Inscrit en
    Octobre 2011
    Messages
    281
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 281
    Points : 161
    Points
    161
    Par défaut
    Merci pour le conseil, je créerais donc un SQLite local avec mes articles. Mais cela ne répond pas à mon problème comme intégrer le chargement dynamique des items à ma ListView

  4. #4
    Membre extrêmement actif
    Avatar de Ryu2000
    Homme Profil pro
    Étudiant
    Inscrit en
    Décembre 2008
    Messages
    9 820
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Décembre 2008
    Messages : 9 820
    Points : 18 740
    Points
    18 740
    Par défaut
    Si tu utilises des articles stocké en base tu n'auras pas besoin de les charger.

    Cela dit si la question t’intéresse, quelqu'un la posé récemment je crois :
    http://www.developpez.net/forums/d12...nees-listview/

    Mais aussi bien ce n'est pas important, là tu récupéras un Cursor, tu rempliras une ListView avec ce Cursor, tu n'auras pas à télécharger de nouveaux articles en descendant la liste, tu les auras déjà téléchargé avant.

Discussions similaires

  1. Comment ajouter plusieurs données dynamiques dans un item d'une listview
    Par Rohan21 dans le forum Composants graphiques
    Réponses: 2
    Dernier message: 02/08/2014, 16h50
  2. Nombre dynamique des items d'une ListView
    Par edhecasa dans le forum Composants graphiques
    Réponses: 3
    Dernier message: 10/09/2013, 12h55
  3. [Débutant] [VB-WPF] - Ajouter un controle dans un item d'une listview ?
    Par troxsa dans le forum VB.NET
    Réponses: 3
    Dernier message: 20/07/2012, 09h33
  4. Ajouter un item dans une listView
    Par vto59 dans le forum C#
    Réponses: 5
    Dernier message: 04/02/2010, 16h23
  5. Changer dynamiquement la couleur d'un item d'une listview
    Par little_cypress dans le forum C++Builder
    Réponses: 2
    Dernier message: 29/11/2004, 14h46

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