2013-10-17 31 views
1

我從數據庫中獲得第一個數據,listview將顯示數據。目前,當列表被多次調用時,數據將被追加到列表的末尾。清除Android中的ListView?

有沒有辦法來清除列表視圖,使新數據再次在列表視圖

public class AndroidTestActivity extends Activity 
{ 
    JSONArray jArray; 
    String result = null; 
    InputStream is = null; 
    StringBuilder sb=null; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     Button b1 = (Button) findViewById(R.id.button1); 
     b1.setOnClickListener(new Button.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       EditText tv = (EditText) findViewById(R.id.editView); 
       ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

       //http get 
       try{ 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpGet httpget = new HttpGet("http://192.168.1.132/test.php"); 
        HttpResponse response = httpclient.execute(httpget); 
        HttpEntity entity = response.getEntity(); 
        is = entity.getContent(); 
       }catch(Exception e){ 
        Log.e("log_tag", "Error in http connection"+e.toString()); 
       } 

       //convert response to string 
       try{ 
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
        sb = new StringBuilder(); 
        sb.append(reader.readLine() + "\n"); 

        String line="0"; 
        while ((line = reader.readLine()) != null) { 
         sb.append(line + "\n"); 
        } 

        is.close(); 
        result=sb.toString(); 
       }catch(Exception e){ 
        Log.e("log_tag", "Error converting result "+e.toString()); 
       } 

       //paring data 
       int ct_id; 
       String ct_name;   

       try{ 
        jArray = new JSONArray(result); 
        JSONObject json_data=null; 

        for(int i=0;i<jArray.length();i++){ 
         json_data = jArray.getJSONObject(i); 
         ct_id=json_data.getInt("id"); 
         ct_name=json_data.getString("name"); 
         tv.append(ct_name); 
        } 
       }catch(JSONException e1){ 
       // Toast.makeText(getBaseContext(), "No City Found" ,Toast.LENGTH_LONG).show(); 
       } catch (ParseException e1) { 
        e1.printStackTrace(); 
       } 
      } 
     }); 
    } 
} 

回答

0

的頂端清除陣列或者你在你的ListView Adapter使用對象的ArryList。然後再次將新數據加載到Array/ArrayList並調用adapter.notifyDataSetChanged()方法。

0

從您希望清除的代碼調用這兩個方法 此處適配器是您將ArrayAdapter添加到列表中的一個實例。

adapter.clear() 
adapter.notifyDataSetChanged() 
0

每次創建一個新列表並從數據庫中獲取數據並將舊數據添加到此列表中。

0

只是寫listView.setAdapter(null)你想清除列表視圖..這對我有用..