Partage
  • Partager sur Facebook
  • Partager sur Twitter

[Android] Ajouter items dynamiquement à une ListView

    3 juillet 2012 à 17:31:20

    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é :

    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

    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;
            }
        };
    }
    
    • Partager sur Facebook
    • Partager sur Twitter

    [Android] Ajouter items dynamiquement à une ListView

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown