2012-05-12 192 views
0

下面的代码目前从MySQL数据库中提取数据并将其显示在ListView中。我期望做的是找到一种方法让应用程序每隔一分钟检查一次mysql数据库以检查是否有新条目,如果它发现一个不在当前ListView中的新条目 - 它将预先添加新条目项目列表的顶部。我已经阅读了一些关于notifyDataSetChanged()的内容,但我想我无法理解它是如何工作的或者如何实现它。任何帮助appriciated。谢谢!Android - 自动将项目添加到ListView

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; 
    } 
} 
+0

调用notifyDataSetChanged()在onPostExecute方法。 – adatapost

+0

所以,只需调用notiftyDataSetChanged()它会不断检查数据库中的新项目?出于某种原因,我无法想象它是那么简单...... – dschuett

回答

0

我会建议您在解析XML对象后将所有内容存储在本地sql数据库中。这样你就可以在内容提供者上使用LoaderManager,并且当新的东西被添加到数据库时它会被异步更新。

它可能要采取当前的代码的一些重构,但其值得IMO,因为它几乎你在找什么