2016-06-16 61 views
0

我一直在研究一個android項目,我需要從服務器獲取數據並在列表視圖中顯示。第一次檢索成功完成,但是從第二次檢索開始,取出的數據放在先前提取的數據下面。我如何刷新列表視圖來查看列表視圖中提取的數據?我使用的代碼如下。從服務器獲取數據時Listview刷新

package com.example.sohan.patient; 

import android.app.Fragment; 
import android.app.FragmentManager; 
import android.app.FragmentTransaction; 
import android.content.Context; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.BaseAdapter; 
import android.widget.Button; 
import android.widget.ListView; 
import android.widget.Spinner; 
import android.widget.TextView; 
import android.widget.Toast; 

import org.json.JSONArray; 
import org.json.JSONObject; 

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.net.URLEncoder; 
import java.util.ArrayList; 
import java.util.List; 

/** 
* Created by Sohan on 5/20/2016. 
*/ 
public class Doctors_layout extends Fragment implements AdapterView.OnItemSelectedListener{ 

    View myView; 
    Spinner spinner; 
    String selectedCity; 
    Context myContext; 
    String jsonResult; 
    JSONObject jsonObject; 
    JSONArray jsonArray; 
    ContactAdapter contactAdapter; 
    String JSON_String; 
    ListView listView; 
    Button button; 

    int check=0; 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     myView = inflater.inflate(R.layout.doctors_directory, container, false); 
     myContext = inflater.getContext(); 
     contactAdapter = new ContactAdapter(myContext, R.layout.row_layout); 
     spinner = (Spinner)myView.findViewById(R.id.spinner); 
     listView = (ListView)myView.findViewById(R.id.listView); 
     listView.setAdapter(contactAdapter); 
     spinner.setOnItemSelectedListener(this); 
     List<String> city = new ArrayList<String>(); 
     city.add("Choose a City"); 
     city.add("Chittagong"); 
     city.add("Dhaka"); 
     ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(myContext, android.R.layout.simple_spinner_item ,city); 
     aAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     spinner.setAdapter(aAdapter); 
     return myView; 
    } 

    @Override 
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
     //contactAdapter.notifyDataSetChanged(); 

     if(check==0) { 
      ((TextView) parent.getChildAt(0)).setTextSize(21); 
      if (position == 0) { 
       nothing(); 
      } else { 
       check++; 
       selectedCity = parent.getItemAtPosition(position).toString(); 
       Toast.makeText(myContext, "Check value: "+check, Toast.LENGTH_LONG).show(); 
       retrieveInfo ri = new retrieveInfo(); 
       ri.execute(selectedCity); // notifydata 
      } 
     } 
     else{ 
      contactAdapter.notifyDataSetChanged(); 
      selectedCity = parent.getItemAtPosition(position).toString(); 
      retrieveInfo ri = new retrieveInfo(); 
      ri.execute(selectedCity); 
     } 



    } 


    @Override 
    public void onNothingSelected(AdapterView<?> parent) { 

    } 

    public void nothing(){ 
     //Toast.makeText(myContext, "Default position 0", Toast.LENGTH_LONG).show(); 
    } 




    class retrieveInfo extends AsyncTask<String, Void, String> {    // send data to server 

     String myUrl; 


     protected void onPreExecute() { 
      myUrl ="http://bdpricelist.com/patient/retrieveMedicalName.php"; // change php script 
     } 


     protected String doInBackground(String... args) { 
      String city; 
      String result = null; 
      city = args[0]; 
      JSONArray jsonArray = null; 
      try{ 
       URL url = new URL(myUrl); 
       HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
       httpURLConnection.setRequestMethod("POST"); 
       httpURLConnection.setDoOutput(true); 
       OutputStream outputStream = httpURLConnection.getOutputStream(); 
       BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); 
       String data_to_send = URLEncoder.encode("city", "UTF-8")+"="+URLEncoder.encode(city,"UTF-8"); 
       bufferedWriter.write(data_to_send); 
       bufferedWriter.flush(); 
       bufferedWriter.close(); 
       outputStream.close(); 
       InputStream is = httpURLConnection.getInputStream(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); 
       StringBuilder sb = new StringBuilder(); 


       while ((JSON_String = reader.readLine()) != null) 
       { 
        sb.append(JSON_String+"\n"); 
       } 
       reader.close(); 
       httpURLConnection.disconnect(); 
       is.close(); 
       return sb.toString().trim(); 
      }catch(MalformedURLException e){ 
       e.printStackTrace(); 
      }catch(IOException f){ 
       f.printStackTrace(); 
      } 
      return null; 
     } 


     protected void onPostExecute(String result) { 

      jsonResult = result; 
      parseJSON(jsonResult); 
      //jsonResult=""; 

     } 
    } 

    public void delete(String city) { 
     Fragment Dl = new Doctors_layout(); 
     FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); 
     fragmentTransaction.replace(R.id.content_frame, Dl); 
     fragmentTransaction.addToBackStack(null); 
     fragmentTransaction.commit(); 
    } 


    public void parseJSON(String json){ 
     Contacts contacts=null; 
      try { 
       jsonObject = new JSONObject(json); 
       jsonArray = jsonObject.getJSONArray("patient"); 
       int count = 0; 
       String name; 
       while (count < jsonArray.length()) { 
        JSONObject jo = jsonArray.getJSONObject(count); 
        name = jo.getString("Medical");       // data's are send to store in and print in listview 
        contacts = new Contacts(name); 
        contactAdapter.add(contacts); 
        count++; 
       } 

       //contactAdapter.add(contacts.getMedicalName()); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
    } 
} 


And my adapter class is given below 


package com.example.sohan.patient; 

import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.BaseAdapter; 
import android.widget.TextView; 
import android.widget.Toast; 

import java.util.ArrayList; 
import java.util.List; 

/** 
* Created by Sohan on 6/9/2016. 
*/ 
public class ContactAdapter extends ArrayAdapter { 
    //ContactHolder contactHolder; 
    List list = new ArrayList(); 
    ContactAdapter contactAdapter; 
    List receivedList = new ArrayList(); 
    View row; 
    ContactHolder contactHolder; 
    int count =0; 
    public ContactAdapter(Context context, int resource) { 
     super(context, resource); 
    } 


    public void add(Contacts object) { 
      // list.clear(); 
      super.add(object); 
      list.add(object); 
      //notifyDataSetChanged(); 
      Toast.makeText(getContext().getApplicationContext(), "Entry without delete ", Toast.LENGTH_SHORT).show(); 
    } 


    @Override 
    public int getCount() { 
     return list.size(); 
    } 

    @Override 
    public void clear() { 
     super.clear(); 
    } 

    @Override 
    public boolean isEmpty() { 
     return super.isEmpty(); 
    } 

    @Override 
    public void notifyDataSetChanged() { 
     super.notifyDataSetChanged(); 
    } 

    public void deleteEntry(){ 
     list.clear(); 
      Toast.makeText(getContext().getApplicationContext(), "List cleared before entry ", Toast.LENGTH_SHORT).show(); 
    } 




    @Override 
    public Object getItem(int position) { 
     return list.get(position); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     //count++; 
     row = convertView; 

     if(row==null){ 
      LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      row = layoutInflater.inflate(R.layout.row_layout,parent,false); 
      contactHolder = new ContactHolder(); 
      contactHolder.MedicalName =(TextView) row.findViewById(R.id.textView5); 
      row.setTag(contactHolder); 
     } 
     else{ 

      contactHolder = (ContactHolder)row.getTag(); 
     } 

     contactHolder = new ContactHolder(); 
     contactHolder.MedicalName =(TextView) row.findViewById(R.id.textView5); 

     Contacts contacts = (Contacts)this.getItem(position); 
     contactHolder.MedicalName.setText(contacts.getMedicalName()); 
     return row; 



    } 

    static class ContactHolder{ 
     TextView MedicalName; 
    } 


} 
+0

是否要取代舊的數據? – Rohit5k2

+0

是的,我想替換舊的數據.. –

回答

0

而不必添加(聯繫對象)在適配器中,有在那裏你清除列表並更新新檢索項目的當前項目的方法。

private void updateContactList(List<Contacts> updatedList) { 
    list.clear(); 
    list.addAll(updatedList); 
    notifyDataSetChanged(); 
} 

和內部parseJSON(JSON字符串)

List<Contacts> newList = new ArrayList<>(); 
while (count < jsonArray.length()) { 
    JSONObject jo = jsonArray.getJSONObject(count); 
    name = jo.getString("Medical"); 
    contacts = new Contacts(name); 
    newList.add(contacts); 
    count++; 
} 
contactAdapter.updateContactList(newList); 
+0

儘管您的解決方案看起來很完美,但應用程序崩潰了。實際上,在我的代碼中,add方法逐個添加listview中的每個條目,現在我試圖在add方法中發送arraylist,它正面臨着問題。 –

+0

Thnxx a tonnnnn。它的工作,保持良好的工作.. :-) –

+0

@MuhitunAzadSohan很高興我能幫助!考慮如果你發現它有用,請將我的答案標記爲「已接受」。 此外,如果您想使用添加(聯繫人對象)方法添加完整列表,只需將您的參數從「聯繫人對象」更改爲「列出對象」。 – 12vi6

0

新數據在舊數據之後,因爲你是在parseJSON()添加新數據到現有的示出了一個。

如果您想用新的數據替換舊數據,請從onCreateView中刪除這些行,並在while循環後面添加parseJSON()

contactAdapter = new ContactAdapter(myContext, R.layout.row_layout); 
listView.setAdapter(contactAdapter); 
+0

不,應用程序崩潰.. –

+0

你能發佈崩潰日誌嗎? – Rohit5k2