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:
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:
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;
}
};
} |