我试图从 Web 服务器上的数据库(联系人集)中检索数据,并尝试使用 ListViews 显示数据。每当我运行我的应用程序时,每次它都会将相同的列表项添加到列表中。该图像将更好地解释它:
这是我第一次运行我的应用程序(安装后)。现在我退出我的应用程序并再次运行它。结果是:
这是我的应用程序的代码:
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”。但是每次我运行我的应用程序时,都会添加相同的列表视图项。我想要的只是显示一次。请问这里有人可以吗??
谢谢,