2015-11-03 65 views
0

我做了一個簡單的代碼來從MySQL數據庫檢索一些數據,並把它們放到android listview中一切正常,但舊的項目停留在列表視圖,它添加了新的項目(數據被複制),下面是php代碼:如何在不復制數據的情況下自動刷新(添加/更新)listview項目?

$sql = "SELECT * FROM persons"; 

$res = mysqli_query($con,$sql); 

$result = array(); 

while($row = mysqli_fetch_array($res)){ 
array_push($result, 
array('id'=>$row[0], 
'name'=>$row[1], 
'address'=>$row[2] 
)); 
} 

echo json_encode(array("result"=>$result)); 

mysqli_close($con); 

這裏了android代碼:

public class FetchData extends Activity{ 
    String myJSON; 

    private static final String TAG_RESULTS="result"; 
    private static final String TAG_ID = "id"; 
    private static final String TAG_NAME = "name"; 
    private static final String TAG_ADD ="address"; 

    JSONArray peoples = null; 

    ArrayList<HashMap<String, String>> personList; 

    ListView list; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.test); 
     list = (ListView) findViewById(R.id.listView); 
     personList = new ArrayList<HashMap<String,String>>(); 
     getData(); 
     final Handler handler = new Handler(); 
     handler.postDelayed(new Runnable() { 

      @Override 
      public void run() { 


       refreshData(); 
       handler.postDelayed(this, 2 * 100); 
      } 
     }, 2 * 100); 

    } 
    public void refreshData(){ 

    } 
    public void getData(){ 
     class GetDataJSON extends AsyncTask<String, Void, String>{ 

      @Override 
      protected String doInBackground(String... params) { 
       DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 
       HttpPost httppost = new HttpPost("http://192.168.1.4/get-data.php"); 

       // Depends on your web service 
       httppost.setHeader("Content-type", "application/json"); 

       InputStream inputStream = null; 
       String result = null; 
       try { 
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity(); 

        inputStream = entity.getContent(); 
        // json is UTF-8 by default 
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
        StringBuilder sb = new StringBuilder(); 

        String line = null; 
        while ((line = reader.readLine()) != null) 
        { 
         sb.append(line + "\n"); 
        } 
        result = sb.toString(); 
       } catch (Exception e) { 
        // Oops 
       } 
       finally { 
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){} 
       } 
       return result; 
      } 

      @Override 
      protected void onPostExecute(String result){ 
       myJSON=result; 

       showdata(); 
      } 
     } 
     GetDataJSON g = new GetDataJSON(); 
     g.execute(); 
    } 
    protected void showdata(){ 
     try { 
      JSONObject jsonObj = new JSONObject(myJSON); 
      peoples = jsonObj.getJSONArray(TAG_RESULTS); 

      for(int i=0;i<peoples.length();i++){ 
       JSONObject c = peoples.getJSONObject(i); 
       String id = c.getString(TAG_ID); 
       String name = c.getString(TAG_NAME); 
       String address = c.getString(TAG_ADD); 

       HashMap<String,String> persons = new HashMap<String,String>(); 

       persons.put(TAG_ID,id); 
       persons.put(TAG_NAME,name); 
       persons.put(TAG_ADD,address); 

       personList.add(persons); 
      } 

      ListAdapter adapter = new SimpleAdapter(
        FetchData.this, personList, R.layout.list_item, 
        new String[]{TAG_ID,TAG_NAME,TAG_ADD}, 
        new int[]{R.id.id, R.id.name, R.id.address} 
      ); 

      list.setAdapter(adapter); 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

    } 


    } 

我想如果MySQL數據庫中的數據改變爲具體的項目自動更新特定列表視圖項,並添加新項目,而無需複製

回答

1

嘗試修改您的showdata()這樣的:

protected void showdata(){ 
     try { 
      JSONObject jsonObj = new JSONObject(myJSON); 
      peoples = jsonObj.getJSONArray(TAG_RESULTS); 

      personList.clear(); 
      for(int i=0;i<peoples.length();i++){ 
       JSONObject c = peoples.getJSONObject(i); 
       String id = c.getString(TAG_ID); 
       String name = c.getString(TAG_NAME); 
       String address = c.getString(TAG_ADD); 

       HashMap<String,String> persons = new HashMap<String,String>(); 

       persons.put(TAG_ID,id); 
       persons.put(TAG_NAME,name); 
       persons.put(TAG_ADD,address); 

       personList.add(persons); 
      } 

      ListAdapter adapter = new SimpleAdapter(
        FetchData.this, personList, R.layout.list_item, 
        new String[]{TAG_ID,TAG_NAME,TAG_ADD}, 
        new int[]{R.id.id, R.id.name, R.id.address} 
      ); 

      list.setAdapter(adapter); 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

    } 

personList.clear(); - 清洗舊的結果。

0

來解決這個問題,從PHP文件 恢復,所以你不會看到任何重複數據最後一個ID發送,會默認加載多個項目發送ID爲零,並在每次發出請求發送存儲

最後一個ID時間的最佳方式
$id = abs(intval($_GET['id'])); 
$sql = "SELECT * FROM persons where id > ".$id; 
$res = mysqli_query($con,$sql); 
$result = array(); 

while($row = mysqli_fetch_array($res)){ 
array_push($result, 
array('id'=>$row[0], 
'name'=>$row[1], 
'address'=>$row[2] 
)); 
} 

echo json_encode(array("result"=>$result)); 

mysqli_close($con); 

Java類

public class FetchData extends Activity{ 
String myJSON; 

private static final String TAG_RESULTS="result"; 
private static final String TAG_ID = "id"; 
private static final String TAG_NAME = "name"; 
private static final String TAG_ADD ="address"; 

JSONArray peoples = null; 

ArrayList<HashMap<String, String>> personList; 

ListView list; 
private static int lastid = 0; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.test); 
    list = (ListView) findViewById(R.id.listView); 
    personList = new ArrayList<HashMap<String,String>>(); 
    getData(); 
    final Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 

     @Override 
     public void run() { 


      refreshData(); 
      handler.postDelayed(this, 2 * 100); 
     } 
    }, 2 * 100); 

} 
public void refreshData(){ 

} 
public void getData(){ 
    class GetDataJSON extends AsyncTask<String, Void, String>{ 

     @Override 
     protected String doInBackground(String... params) { 
      DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 
      HttpPost httppost = new HttpPost("http://192.168.1.4/get-data.php?id="+lastid); 

      // Depends on your web service 
      httppost.setHeader("Content-type", "application/json"); 

      InputStream inputStream = null; 
      String result = null; 
      try { 
       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity entity = response.getEntity(); 

       inputStream = entity.getContent(); 
       // json is UTF-8 by default 
       BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
       StringBuilder sb = new StringBuilder(); 

       String line = null; 
       while ((line = reader.readLine()) != null) 
       { 
        sb.append(line + "\n"); 
       } 
       result = sb.toString(); 
      } catch (Exception e) { 
       // Oops 
      } 
      finally { 
       try{if(inputStream != null)inputStream.close();}catch(Exception squish){} 
      } 
      return result; 
     } 

     @Override 
     protected void onPostExecute(String result){ 
      myJSON=result; 

      showdata(); 
     } 
    } 
    GetDataJSON g = new GetDataJSON(); 
    g.execute(); 
} 
protected void showdata(){ 
    try { 
     JSONObject jsonObj = new JSONObject(myJSON); 
     peoples = jsonObj.getJSONArray(TAG_RESULTS); 

     for(int i=0;i<peoples.length();i++){ 
      JSONObject c = peoples.getJSONObject(i); 
      String id = c.getString(TAG_ID); 
      String name = c.getString(TAG_NAME); 
      String address = c.getString(TAG_ADD); 

      HashMap<String,String> persons = new HashMap<String,String>(); 

      persons.put(TAG_ID,id); 
      persons.put(TAG_NAME,name); 
      persons.put(TAG_ADD,address); 

      personList.add(persons); 
      lastid = Integer.parseInt(id); 
     } 

     ListAdapter adapter = new SimpleAdapter(
       FetchData.this, personList, R.layout.list_item, 
       new String[]{TAG_ID,TAG_NAME,TAG_ADD}, 
       new int[]{R.id.id, R.id.name, R.id.address} 
     ); 

     list.setAdapter(adapter); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

} 


} 
相關問題