我試圖從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'是一個靜態變量,它可以保持更長的時間,你想要的。在啓動您的異步任務之前,您需要清除該列表。 –