The code below currently pulls data from a mysql database and displays it in a ListView. What I am looking to do is find a way to have the application check the mysql database every minute or so to check for any new entries, and if it finds a new entry that isn't in the current ListView - it will prepend the new item(s) to the top of the list. I have read a few things on notifyDataSetChanged(), but I guess I can't grasp how it actually works or how to implement it. Any Help is appriciated. Thanks!
public class Data extends ListActivity {
private ArrayList<Feed> posts = new ArrayList<Feed>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new FeedTask().execute();
}
private class FeedTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Data.this,"", "Loading. Please wait...", true);
}
@Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://xxxx/livefeed/getdata.php");
HttpResponse httpResponse = httpClient.execute(httpPost);
String result = EntityUtils.toString(httpResponse.getEntity());
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
Feed feed = new Feed();
feed.content = json_data.getString("post");
feed.time = json_data.getString("post_time");
posts.add(feed);
}
}
catch (Exception e){
Log.e("ERROR", "Error loading JSON", e);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setListAdapter(new FeedListAdaptor(Data.this, R.layout.feed, posts));
}
}
private class FeedListAdaptor extends ArrayAdapter<Feed> {
private ArrayList<Feed> posts;
public FeedListAdaptor(Context context,
int textViewResourceId,
ArrayList<Feed> items) {
super(context, textViewResourceId, items);
this.posts = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.feed, null);
}
Feed o = posts.get(position);
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
tt.setText(o.content);
bt.setText(o.time);
return v;
}
}
public class Feed {
String content;
String time;
}
}