从服务器获取数据时Listview刷新

时间:2016-06-16 18:43:26

标签: android listview

我一直在研究一个Android项目,我需要从服务器获取数据并在列表视图中显示。第一次检索成功完成,但从第二次检索开始,所取出的数据被放置在先前获取的数据之下。如何刷新列表视图以查看列表视图中的提取数据?我使用的代码如下。

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;
    }


}

2 个答案:

答案 0 :(得分:0)

新数据显示在旧数据之后,因为您要将新数据添加到parseJSON()中的现有数据。

如果您要使用新数据替换旧数据,请从onCreateView删除这些行,并在parseJSON()循环后立即添加到while内。

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

答案 1 :(得分:0)

不要在适配器中添加(Contacts对象),而是使用一种方法清除列表中的当前项并使用新检索的项进行更新。

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

和parseJSON(String 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);