SearchView返回旧的ListView位置值Android

时间:2016-04-21 11:25:39

标签: java android listview searchview

我遇到了问题。就像我在SearchView中输入数据一样,新数据已过滤并显示在ListView中。但是,当我从此过滤的listview。中选择一个条目时,它会根据先前ListView的位置(即未过滤的数据)返回数据。在下面,我发布了我的代码。请仔细检查并帮助我。谢谢。

CustomAdapter.java

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

import java.util.ArrayList;

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

import java.util.ArrayList;
import java.util.logging.Filter;

public class CustomAdapter extends ArrayAdapter < State > implements Filterable {
 int groupid;
 ArrayList < State > records;
 ArrayList < State > filterRecords;
 CustomFilter filter;
 Context context;
 public CustomAdapter(Context context, int vg, int id, ArrayList < State >
  records) {
  super(context, vg, id, records);
  this.context = context;
  groupid = vg;
  this.records = records;
  this.filterRecords = records;
 }
 @Override
 public int getCount() {
  return records.size();
 }
 @Override
 public State getItem(int position) {
  return records.get(position);
 }
 @Override
 public long getItemId(int position) {
  return records.indexOf(getItem(position));
 }
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  View itemView = inflater.inflate(groupid, parent, false);
  TextView textName = (TextView) itemView.findViewById(R.id.state_name);
  textName.setText(records.get(position).getpName());
  return itemView;
 }
 @Override
 public android.widget.Filter getFilter() {
  if (filter == null) {
   filter = new CustomFilter();
  }
  return filter;
 }

 class CustomFilter extends android.widget.Filter {
  @Override
  protected FilterResults performFiltering(CharSequence constraint) {
   FilterResults results = new FilterResults();
   if (constraint != null && constraint.length() > 0) {
    //constraint to upper
    constraint = constraint.toString().toUpperCase();
    ArrayList < State > filters = new ArrayList < State > ();

    for (int i = 0; i < filterRecords.size(); i++) {
     if (filterRecords.get(i).getpName().toUpperCase().contains(constraint)) {
      State p = new State(filterRecords.get(i).getpName());
      //p.setpName(filterRecords.get(i).getpName());
      filters.add(p);

     }

    }
    results.count = filters.size();
    results.values = filters;
   } else {
    results.count = filterRecords.size();
    results.values = filterRecords;
   }
   return results;
  }
  @Override
  protected void publishResults(CharSequence constraint, FilterResults results) {
   records = (ArrayList < State > ) results.values;
   notifyDataSetChanged();
  }
 }
}

返回数据的类 的 State.java

public class State {
    private String pName;
    public State( String pName)
    {
        this.pName=pName;
    }
    public void setpName(String pName){this.pName=pName;}
    public String getpName(){return pName;}
}

StateDetail.java

public class StateDetail extends AppCompatActivity {
 String[] items;
 CustomAdapter adapter4;
 ListView listProduct;
 ArrayList < State > records;
 ArrayList < State > FilteredState;
 Activity context;
 ProgressDialog pd;
 SearchView SVstate;
 String sText = null;
 public ListView getState1() {
  listProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView < ? > parent, View view, int position, long id) {

     String selected = records.get(position).getpName();
     Intent i = new Intent(getApplicationContext(), Search.class);
     i.putExtra("fld_state_name", selected);
     setResult(RESULT_OK, i);
     finish();
    });
   return null;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_state_detail);
   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(toolbar);

   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
   context = this;
   records = new ArrayList < State > ();
   FilteredState = new ArrayList < State > ();
   listProduct = (ListView) findViewById(R.id.StateList);

   adapter4 = new CustomAdapter(context, R.layout.state_listview, R.id.state_name,
    records);
   listProduct.setAdapter(adapter4);
   SVstate = (SearchView) findViewById(R.id.SVState);
   SVstate.setQueryHint("Search....");
   int id = SVstate.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
   TextView textView = (TextView) SVstate.findViewById(id);
   textView.setTextColor(Color.BLACK);
   SVstate.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String text) {
     return false;
    }
    @Override
    public boolean onQueryTextChange(String text) {
     adapter4.getFilter().filter(text);
     //adapter4.notifyDataSetChanged(); //notify the ListView to get new records
     return false;
    }
   });
  }
  class BackTask extends AsyncTask < String, Void, String > {
   String textSearch;
   @Override
   protected String doInBackground(String...param) {
    {
     InputStream is = null;
     String result = "";
     try {
      HttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost("http://10.0.2.2/getState.php");
      HttpResponse response = httpClient.execute(httpPost);
      HttpEntity entity = response.getEntity();
     } catch (Exception e) {
      if (pd != null)
       pd.dismiss(); //close the dialog if error occurs
      Log.e("ERROR", e.getMessage());
     }
     //convert response to string
     try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 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) {
      Log.e("ERROR", "Error converting result " + e.toString());
     }
     //parse json data
     try {
      // Remove unexpected characters that might be added to beginning of the
      result = result.substring(result.indexOf("["));
      JSONArray jArray = new JSONArray(result);
      for (int i = 0; i < jArray.length(); i++) {
       JSONObject json_data = jArray.getJSONObject(i);
       State p = new State(json_data.getString("fld_state_name"));
       //  p.setpName(json_data.getString("fld_state_name"));
       records.add(p);
       for (int j = 0; j < records.size(); j++) {
        if (records.get(j).getpName().equals(p.getpName())) {
         String matchFound = "Y";
         //   Filiter
        }
       }
      }
      getState1();
     } catch (Exception e) {
      Log.e("ERROR", "Error passing data " + e.toString());
     }
     return null;
    }
   }
   protected void onPreExecute() {
    super.onPreExecute();
    pd = new ProgressDialog(context);
    pd.setTitle("Retrieving data");
    pd.setMessage("Please wait.");
    pd.setCancelable(true);
    pd.setIndeterminate(true);
    pd.show();
   }
   protected void onPostExecute(Void result) {
    if (pd != null) pd.dismiss(); //close dialog
    Log.e("size", records.size() + "");
    adapter4.notifyDataSetChanged(); //notify the ListView to get new records
   }
  }
  public void onStart() {
   super.onStart();
   BackTask bt = new BackTask();
   bt.execute();
  }
}

1 个答案:

答案 0 :(得分:0)

您应该从筛选列表或适配器视图中获取数据。记录

string fMoney;
fMoney = money.ToString("C");
return fMoney;