listview上的搜索过滤器在项目点击时返回错误的位置

时间:2016-08-03 04:24:06

标签: android baseadapter

我有listview,在点击项目后过滤listview的项目时,它总是返回listview项目的错误位置。

以下是适配器类:

public class AdmitPatientAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
ArrayList<HashMap<String, String>> TempArrList = new ArrayList<>();
private static LayoutInflater inflater = null;
public static final String TAG_MRDNO = "mrd_no";


public AdmitPatientAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data = d;
    TempArrList.addAll(d);
    inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);


}


public int getCount() {
    return TempArrList.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    TempArrList.clear();
    if (charText.length() == 0) {
        TempArrList.addAll(data);

    } else {
        HashMap<String, String> tMap;
        for (int i = 0; i < data.size(); i++) {
            tMap = data.get(i);
            if (charText.length() != 0 && tMap.get("mrd_no").toLowerCase(Locale.getDefault()).contains(charText)) {//mrd_no
                TempArrList.add(tMap);
            } else if (charText.length() != 0 && tMap.get("pname").toLowerCase(Locale.getDefault()).contains(charText)) {//pname
                TempArrList.add(tMap);
            } else if (charText.length() != 0 && tMap.get("bed_no").toLowerCase(Locale.getDefault()).contains(charText)) {
                TempArrList.add(tMap);
            } else if (charText.length() != 0 && tMap.get("nursingstation").toLowerCase(Locale.getDefault()).contains(charText)) {
                TempArrList.add(tMap);
            }

        }
        notifyDataSetChanged();
    }

}

public View getView(int position, View convertView, ViewGroup parent) {

    View viw = convertView;
    if (convertView == null)
        viw = inflater.inflate(R.layout.ip_ptn_items, null);
    TextView txt_Mr_dno = (TextView) viw.findViewById(R.id.txtMrdno);
    TextView txt_pitnt_Name = (TextView) viw.findViewById(R.id.txtpitntName);
    TextView txt_Bed_no = (TextView) viw.findViewById(R.id.txtBedno);
    TextView txt_Dob = (TextView) viw.findViewById(R.id.txtDob);

    TextView txt_drNme = (TextView) viw.findViewById(R.id.txtDr);
    TextView txt_Sex = (TextView) viw.findViewById(R.id.txtSex);
    TextView txt_Wrdnm = (TextView) viw.findViewById(R.id.txtWrdnm);

    HashMap<String, String> item = new HashMap<String, String>();
    item = TempArrList.get(position);
    String mrd_no = item.get(TAG_MRDNO);
    item.put(TAG_MRDNO, mrd_no);
    mrd_no = item.get(TAG_MRDNO);

    if (mrd_no.endsWith("*")) {
        txt_Mr_dno.setTextColor(Color.RED);
        txt_pitnt_Name.setTextColor(Color.RED);
        txt_Dob.setTextColor(Color.RED);
        txt_Sex.setTextColor(Color.RED);
        txt_Wrdnm.setTextColor(Color.RED);
        txt_Bed_no.setTextColor(Color.RED);


    } else {
        txt_Mr_dno.setTextColor(Color.BLACK);
        txt_pitnt_Name.setTextColor(Color.BLACK);
        txt_Dob.setTextColor(Color.BLACK);
        txt_Sex.setTextColor(Color.BLACK);
        txt_Wrdnm.setTextColor(Color.BLUE);
        txt_Bed_no.setTextColor(Color.BLUE);

    }

    //Setting all values in listview
    txt_Mr_dno.setText(item.get("mrd_no"));
    txt_pitnt_Name.setText(item.get("pname"));
    txt_Bed_no.setText(item.get("bed_no"));
    txt_Dob.setText(item.get("dob"));
    //txt_admit_Date.setText(item.get("admission_date"));
    txt_Sex.setText(item.get("sex"));
    txt_Wrdnm.setText(item.get("nursingstation"));
    txt_drNme.setText(item.get("doctor"));


    //  item = data.get(position);
    ///  String userType = item.get(TAG_UTYPE);
    //  item.put(TAG_UTYPE, mrd_no);
    //  userType = item.get(TAG_UTYPE);

    try {
        if (item.get("userType").equals("doctor")) {
            txt_drNme.setVisibility(View.INVISIBLE);
        } else {
            txt_drNme.setVisibility(View.VISIBLE);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return viw;

}


}

另一个是点击事件类:

public class AdmitPatientFragment extends Fragment implements FragmentCycle {


ListView lstViw;
AdmitPatientAdapter adapter;
String DcId = "";
String userType = "";
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPreferences;


// generic array list
ArrayList<HashMap<String, String>> dlst = new ArrayList<HashMap<String, String>>();

// json url
private static String url = "http://scanweb.dmhospital.org:81/amrita_login/AdmList.php?auth=Yes";


@Override
public void onResumeFragment() {

}

@Override
public void onPauseFragment() {

}


// json node names
private static final String TAG_ADMITLIST = "AdmissionList";
private static final String TAG_MRD = "mrd_no";
private static final String TAG_PNAME = "pname";
private static final String TAG_BNO = "bed_no";
private static final String TAG_DOB = "dob";
private static final String TAG_ADMIT_DATE = "admission_date";
private static final String TAG_DOCTOR = "doctor";
private static String TAG_SEX = "sex";
private static String TAG_PATN_ID = "patient_id";
private static String TAG_VISIT_ID = "visit_id";
private static final String TAG_WARD_NAME = "nursingstation";
public static final String TAG_UTYPE = "userType";

JSONArray AdmissionList = null;

public AdmitPatientFragment() {

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    setReturnTransition(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    LinearLayout rootView = (LinearLayout) inflater.inflate(
            R.layout.ip_ptn_lstviw, container, false);

    dlst = new ArrayList<HashMap<String, String>>();
    Intent intent = getActivity().getIntent();
    DcId = intent.getStringExtra("drid");


    if (CheckNetwork.isInternetAvailable(getActivity())) //returns true if internet available
    {


    } else {
        Toast.makeText(getActivity(), "No Internet Connection", Toast.LENGTH_SHORT).show();
    }


    // to read doctor id from shared preferences
    sharedPreferences = getActivity().getSharedPreferences(MyPREFERENCES,
            Context.MODE_PRIVATE);
    DcId = sharedPreferences.getString("drid", DcId);
    userType = sharedPreferences.getString("usertype", userType);

    url = url + "&docID=" + DcId;

    new paAsyncTask().execute();


    return rootView;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.three_dots_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
    final MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
    //*** setOnQueryTextFocusChangeListener ***
    searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {

        }
    });

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String searchQuery) {
            adapter.filter(searchQuery.toString().trim());
            lstViw.invalidate();
            return true;
        }
    });

    MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            // Do something when collapsed
            return true;  // Return true to collapse action view
        }

        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            // Do something when expanded
            return true;  // Return true to expand action view
        }
    });

}


private class paAsyncTask extends AsyncTask<String, String, JSONObject> {
    ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        try {
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait admit patient list is loading ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        return json;
    }

    @Override
    protected void onPostExecute(JSONObject json) {

        pDialog.dismiss();

        try {
            // Getting JSON Array from URL
            AdmissionList = json.getJSONArray(TAG_ADMITLIST);
            dlst = new ArrayList<HashMap<String, String>>();
            for (int i = 0; i < AdmissionList.length(); i++) {
                JSONObject c = AdmissionList.getJSONObject(i);

                String admission_date = c.getString(TAG_ADMIT_DATE);


                HashMap<String, String> map = new HashMap<String, String>();
                String ageSex = "(" + c.getString(TAG_DOB) + " | " + c.getString(TAG_SEX) + ")";

                String[] admDte = admission_date.split(":");
                String[] admDte1 = admission_date.split(":");


                String resultDte = admDte[0] + ":" + admDte1[1];

                map.put(TAG_MRD, c.getString(TAG_MRD).toString());
                map.put(TAG_PNAME, c.getString(TAG_PNAME));
                map.put(TAG_BNO, c.getString(TAG_BNO));

                map.put(TAG_DOB, ageSex);
                map.put(TAG_ADMIT_DATE, resultDte);
                map.put(TAG_UTYPE, userType);
                map.put(TAG_DOCTOR, c.getString(TAG_DOCTOR).toString());
                // map.put(TAG_SEX, str);
                map.put(TAG_WARD_NAME, c.getString(TAG_WARD_NAME));
                map.put(TAG_PATN_ID, c.getString(TAG_PATN_ID));
                map.put(TAG_VISIT_ID, c.getString(TAG_VISIT_ID));


                dlst.add(map);
            }

            lstViw = (ListView) getView().findViewById(R.id.lstAdmsion);
            adapter = new AdmitPatientAdapter(getActivity(), dlst);
            adapter.notifyDataSetChanged();
            lstViw.setAdapter(adapter);


            lstViw.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent,
                                        View view, int position, long id) {

                    HashMap<String, String> map = dlst.get(position);
                    Intent imp = new Intent(getActivity(),
                            NavigationDrawerActivity.class);
                    imp.putExtra("drid", DcId);
                    //  imp.putExtra(TAG_ADMIT_DATE, map.get(""));
                    imp.putExtra("docNme", map.get(TAG_DOCTOR));
                    imp.putExtra("ptnId", map.get(TAG_PATN_ID));
                    imp.putExtra("vst_id", map.get(TAG_VISIT_ID));

                    startActivity(imp);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
}

1 个答案:

答案 0 :(得分:1)

尝试更改

HashMap<String, String> map = dlst.get(position);

HashMap<String, String> map = adapter.getItem(position);

基本上,OnItemClickListener是从ListView中获取对象而不是已更新引用的适配器......

编辑1:您还需要在适配器中实现getItem,以便从筛选列表中返回一个对象。我假设那是最好的......

因此,您需要将它放在适配器类中:

public HashMap<String, String>  getItem(int position){
    return dlst.get(position);
}