我试图从Web服务器上的数据库(联系人集合)中检索数据,并尝试使用ListViews显示数据。每当我运行我的应用程序,每次它将相同的列表项添加到列表中。图像将更好地解释它:每次应用程序运行时都添加相同的listview项目
这是我第一次运行我的应用程序(我安装它后)。现在我退出我的应用程序并再次运行它。其结果是:
这里是我的应用程序的代码:
RegisterMe reg=connect.new RegisterMe(); //RegisterMe is an asynchronous task used
reg.execute(myPhoneNumber); // to receive data. execute() fxn is called
// which invokes doInBackground() fxn.
/*try{
Thread.sleep(3000);
}catch(Exception e)
{
System.out.println(e.toString());
} */
adapter=new SimpleAdapter(this,mutualFriends,R.layout.activity_first,new String[]{KEY_NAME,KEY_NUMBER}
,new int[]{R.id.text1,R.id.text2});
setListAdapter(adapter);
代码doInBackground()如下:
protected class RegisterMe extends AsyncTask<String,Void,String>
{
protected String doInBackground(String... str)
{
String myPhoneNumber;
myPhoneNumber=str[0];
InputStream is = null;
String result=new String();
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://johnconnor.comuf.com/register.php");
try
{
List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("mynumber",myPhoneNumber));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response= httpclient.execute(httppost);
Log.i("postData",response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch (ClientProtocolException e) {
Log.e("log_tag", "Error in http connection "+e.toString());
} catch (IOException e) {
}
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
}
result=result.substring(0,result.indexOf('\n'));
return result ; //result contains "Neeraj,"123456789"
}
代码onPostExecute如下:
protected void onPostExecute(String result)
{
String[] array;
array=result.split("[/]");
HashMap<String,String> map=new HashMap<String,String>();
for(int i=0;i<array.length-1;i++)
{
String[] singleContact;
singleContact=array[i].split("[,]");
map.put(FirstActivity.KEY_NAME,singleContact[0]);
map.put(FirstActivity.KEY_NUMBER, singleContact[1]);
FirstActivity.mutualFriends.add(map);
}
FirstActivity.adapter.notifyDataSetChanged();
}
我已经检查使用调试器,结果只包含“Neeraj,123456789”。但是每次运行我的应用程序时,都会添加相同的listview项目。我想要的只是只显示一次。任何人都可以在这里?
感谢,
如果'mutualFriends'是一个静态变量,它可以保持更长的时间,你想要的。在启动您的异步任务之前,您需要清除该列表。 –