listview清空的问题

我在SQLite 中添加新内容之后, 刷新ListView显示,却发现原来的内容没有消失,而是新的内容接在其后。。。
如何在更新之前 清空原有的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();
}
}
});
}
}

没做过手机开发,不过思路很清晰,在调用装载listview之前先清空listview,如listview1.clear(),你只要找到调用listview的入口就解决了。比如:

下面这个计时器,每隔一段时间重新加载一次listview,把内容显示出来,InitListView()方法是装载listview的入口,那么在之前用listView1.Clear()将listview清空即可。其实方法很多啦。

void timer1_Tick(object sender, EventArgs e)
{
   listView1.Clear();
   InitListView();
   timer1.Enabled = true;
}

希望对你有帮助,有问题再追问,望采纳。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-08-25

虽然离你问这个很远了,估计你自己也找到方法了,不过还是纠正一下

其实LS的思路很对,做开发的就该这么想,但是Android中的ListView是没有clear()这个方法的,因此行不通。

一般的,对于要给ListView显示东西,都会使用一个List+Adapter的方案,数据就是List中一个一个item,用adapter进行填充。所以说这就简单了,因为List是有clear()方法的,直接找到ListVIew对应的List执行一次list.clear()就行了。

...
...
listView = this.findViewById(R.id.listView);
adapter = new TAdapter(Main.this);
list = getResult();
//以及其他初始化
...
...
//显示
adapter.bindData(list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
...
...
//清空
adapter.list.clear();      //或者list.clear();adapter.bindData(list);
adapter.notifyDataSetChanged();

相似回答