Android-自动将项目添加到ListView
下面的代码当前从mysql数据库中提取数据,并将其显示在ListView中。我想做的是找到一种方法,让应用程序每隔一分钟左右检查一次mysql数据库,以检查是否有任何新条目,如果它发现一个不在当前ListView中的新条目,它会将新条目放在列表的顶部。我读了一些关于notifyDataSetChanged的文章,但我想我不能理解它是如何工作的,或者如何实现它。任何帮助都是值得的。谢谢Android-自动将项目添加到ListView,android,android-listview,Android,Android Listview,下面的代码当前从mysql数据库中提取数据,并将其显示在ListView中。我想做的是找到一种方法,让应用程序每隔一分钟左右检查一次mysql数据库,以检查是否有任何新条目,如果它发现一个不在当前ListView中的新条目,它会将新条目放在列表的顶部。我读了一些关于notifyDataSetChanged的文章,但我想我不能理解它是如何工作的,或者如何实现它。任何帮助都是值得的。谢谢 public class Data extends ListActivity { private Arr
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;
}
}
我建议在解析XML对象后将所有内容存储在本地sql数据库中。这样,您就可以在内容提供程序上使用,当新的内容添加到数据库时,它将异步更新
这可能需要对当前代码进行一些重构,但在我看来是值得的,因为这正是您需要的调用onPostExecute方法中的notifyDataSetChanged。因此,只需调用notifyDataSetChanged,它就会不断检查数据库中的新项?出于某种原因,我无法想象事情会这么简单。。。