2012-05-12 256 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,因爲它幾乎你在找什麼