Listview Id Changes - android

I have read through the forums and I can't seem to figure out how to get the position of the selected item to match my array list items since the listview is searchable. It works great until I search then my items do not match up. Can someone provide an exact example?
private void displayListView() {
ArrayList<Country> countryList = new ArrayList<Country>();
//countryList.clear();
// int j=1;
for (int i = 0; i < categoriesList.size(); i++) {
//list.add(new ItemData(categoriesList.get(i).getName(), R.drawable.ic_launcher));
//Array list of countries
Country country = new Country(workordertypeId.get(i),ActualCity.get(i),ClientName.get(i),
ProjectNotes.get(i), ProjectStart.get(i),ProjectFieldNotes.get(i),ProjectStatus.get(i));
countryList.add(country);
///////list.add(new StringWithTag(categoriesList.get(i).getName(),categoriesList2.get(i).getName()));
//list.add(new ItemData("testthis",R.drawable.logolong4));
}
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this,
R.layout.country_info, countryList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
//enables filtering for the contents of the given ListView
listView.setTextFilterEnabled(true);
//listView.has
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
setwoindex(position);
//setwoindex (parent.getSelectedItemPosition());
//listView.getItemId(position)
Country country = (Country) parent.getItemAtPosition(position);
//Toast.makeText(getApplicationContext(),
//country.getCode(), Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(),
//country.getRegion(), Toast.LENGTH_SHORT).show();
String haspdf = getIntent().getExtras().getString("haspdf", "defaultKey");
if (haspdf.equals("1")) {
//counter++;
btnAddNewCategory.setText("Save PDF");
btnAddNewCategory.setEnabled(true);
} else if (haspdf.equals("0")) {
btnAddNewCategory.setEnabled(false);
}
if (haspdf.equals("3")) {
//counter++;
btnAddNewCategory.setText("Save Image");
btnAddNewCategory.setEnabled(true);
} else if (haspdf.equals("0")) {
btnAddNewCategory.setEnabled(false);
}
//updateGUI();
//Toast.makeText(getBaseContext(), "test", Toast.LENGTH_SHORT).show();
//spinnerFood.setTag(pos);
if (getwoindex() != null) {
// punchin.setEnabled(true);
Viewattachments.setEnabled(true);
//punchin.setEnabled(true);
// punchout.setEnabled(true);
//btnAddNewCategory.setEnabled(true);
int index = getwoindex();
//Toast.makeText(getBaseContext(),"WorkOrderNumber Toasting="+ workordertypeId.get(index).toString() +" "+ClientName.get(index).toString()+" "+ActualCity.get(index).toString()+" "+ClientPhone.get(index).toString(), Toast.LENGTH_SHORT).show();
FullAddress.setText(WoClientName.get(index).toString() + "\n" + WoClientStreet.get(index).toString() + "\n" + ActualCity.get(index).toString() + " " + WoClientState.get(index).toString() + " " + WoClientZip.get(index).toString());
ActualPhone.setText(WoClientPhone.get(index).toString());
String IdUser = getIntent().getStringExtra("IdUser");
String usernameforlogin = getIntent().getStringExtra("usernameforlogin");
mrcastrovinci();
}
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> originalList;
private ArrayList<Country> countryList;
private CountryFilter filter;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
this.originalList = new ArrayList<Country>();
this.originalList.addAll(countryList);
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public android.widget.Filter getFilter() {
if (filter == null){
filter = new CountryFilter();
}
return filter;
}
private class ViewHolder {
TextView code;
TextView name;
TextView continent;
TextView region;
TextView Dated;
TextView ProjectFieldNotes;
TextView ProjectStatus;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.continent = (TextView) convertView.findViewById(R.id.continent);
holder.region = (TextView) convertView.findViewById(R.id.region);
holder.Dated = (TextView) convertView.findViewById(R.id.dated);
holder.ProjectFieldNotes = (TextView) convertView.findViewById(R.id.ProjectFieldNotes);
holder.ProjectStatus = (TextView) convertView.findViewById(R.id.ProjectStatus);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Country country = countryList.get(position);
holder.code.setText(country.getCode());
holder.name.setText(country.getName());
holder.continent.setText(country.getContinent());
holder.region.setText(country.getRegion());
holder.Dated.setText(country.getDated());
holder.ProjectFieldNotes.setText(country.getProjectFieldNotes());
holder.ProjectStatus.setText(country.getProjectStatus());
return convertView;
}
private class CountryFilter extends android.widget.Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<Country> filteredItems = new ArrayList<Country>();
for(int i = 0, l = originalList.size(); i < l; i++)
{
Country country = originalList.get(i);
if(country.toString().toLowerCase().contains(constraint))
filteredItems.add(country);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = originalList;
result.count = originalList.size();
}
}
return result;
//setwoindex(ListView1.getSelectedItemPosition());
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
countryList = (ArrayList<Country>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = countryList.size(); i < l; i++)
add(countryList.get(i));
notifyDataSetInvalidated();
}
}
}

Would it be acceptable to extend the Country object to contain an id/index?
If yes, that would be stored all the way and you could retrieve it back in the onItemClick for you ListView.
If not, you could build a wrapper around the Country object and either feed that to the adapter or have the adapter construct a list of wrappers.
public class MyWrapper {
public Country mCountry;
public int mOriginalIndex;
}

Yes I actually just extended my country list and included all my items there. I will add an index Id also.

Related

How to prevent my filtered list from clearing?

I have an android app where I have a custom adapter. I want to filter my data but when I clear my edit text my list goes blank.
I want my original list view to be displayed when I clear my edit text. I think my original list is also getting cleared in some code but I do not understand where.
public class Adapter_SelectedDetail extends ArrayAdapter<DataModel> implements Filterable {
private final Context context;
ArrayList<DataModel> MyList=null,newList=null;
private MyFilter filter;
DataModel dataModel;
EditText Mysearch;
ListView listView;
String searchdata;
private static LayoutInflater inflater=null;
public Adapter_SelectedDetail(Context context, EditText search, ArrayList MyList1, ListView listView) {
super(context, -1, MyList1);
this.newList = new ArrayList<DataModel>();
this.newList.addAll(newList);
this.Mysearch=search;
this.listView=listView;
this.MyList = new ArrayList<DataModel>();
this.MyList.addAll(newList);
this.MyList=MyList1;
this.context=context;
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new MyFilter();
}
return filter;
}
#Override
public View getView(final int position, View ConverView, ViewGroup parent) {
inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// DataModel dataModel = (DataModel) getItem(position);
View rowView = ConverView;
// TODO Auto-generated method stub
TextView CompanyName,CompanyMobile,Bill_no,Bill_date,PartyName,Transport,City,
State,CustomerMobileNumber,AgentName,LRno,LRdate,Item,Shades,
AgentMobileNumber,InvoicePDF,PartyEmail,agentEmail;
if (rowView==null) {
rowView = inflater.inflate(R.layout.selected_detail_list_view, parent,false);
}
dataModel=MyList.get(position);
if (dataModel!=null) {
CompanyName = (TextView) rowView.findViewById(R.id.txt_heading_of_detail);
CompanyMobile = (TextView) rowView.findViewById(R.id.txt_subheading_of_detail);
Bill_no = (TextView) rowView.findViewById(R.id.txt_bill_no);
Bill_date = (TextView) rowView.findViewById(R.id.txt_bill_date);
PartyName = (TextView) rowView.findViewById(R.id.txt_party_name);
Transport = (TextView) rowView.findViewById(R.id.txt_transport);
City = (TextView) rowView.findViewById(R.id.txt_city);
State = (TextView) rowView.findViewById(R.id.txt_state);
Shades = (TextView) rowView.findViewById(R.id.txt_shades);
CustomerMobileNumber = (TextView) rowView.findViewById(R.id.txt_customer_mob_no);
AgentName = (TextView) rowView.findViewById(R.id.txt_agent);
AgentMobileNumber = (TextView) rowView.findViewById(R.id.txt_agent_mob_number);
LRdate = (TextView) rowView.findViewById(R.id.txt_lr_date);
LRno = (TextView) rowView.findViewById(R.id.txt_lr_number);
Item = (TextView) rowView.findViewById(R.id.txt_item);
agentEmail = (TextView) rowView.findViewById(R.id.txt_agent_Email);
PartyEmail = (TextView) rowView.findViewById(R.id.txt_party_email);
// Toast.makeText(context, MyList1.get(2).toString(), Toast.LENGTH_SHORT).show();
CompanyMobile.setText(dataModel.getCompanyMobile());
City.setText(dataModel.getCity());
State.setText(dataModel.getState());
CompanyName.setText(dataModel.getCompanyName());
Bill_no.setText(dataModel.getBill_no());
PartyName.setText(dataModel.getPartyName());
Transport.setText(dataModel.getTransport());
Shades.setText(dataModel.getShades());
CustomerMobileNumber.setText(dataModel.getCustomerMobileNumber());
AgentName.setText(dataModel.getAgentName());
AgentMobileNumber.setText(dataModel.getAgentMobileNumber());
LRdate.setText(dataModel.getLRdate());
LRno.setText(dataModel.getLRno());
Item.setText(dataModel.getItem());
agentEmail.setText(dataModel.getAgentEmail());
PartyEmail.setText(dataModel.getPartyEmail());
}
return rowView;
}
public class MyFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<DataModel> filteredItems = new ArrayList<DataModel>();
for(int i = 0, l = MyList.size(); i < l; i++)
{
DataModel dataModel = MyList.get(i);
if(dataModel.getShades().toString().toLowerCase().contains(constraint))
filteredItems.add(dataModel);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = MyList;
result.count = MyList.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
newList = (ArrayList<DataModel>)results.values;
notifyDataSetChanged();
clear();
for (int i = 0, l = newList.size(); i < l; i++)
add(newList.get(i));
notifyDataSetInvalidated();
}
}
}
public class Selected_Detail_Activity extends Activity {
#BindView(R.id.select_listview)
ListView selected_list;
#BindView(R.id.search)
EditText search;
String item, mobile, pass, partyName;
ArrayList<DataModel> MyList1;
Context context;
DataModel dataModel=new DataModel();
#BindView(R.id.txt_party_name)
TextView txtparty_Name;
ConnectionClass connectionClass;
Adapter_SelectedDetail adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selected_detail);
ButterKnife.bind(this);
item = getIntent().getStringExtra("item");
mobile = getIntent().getStringExtra("mobile");
pass = getIntent().getStringExtra("pass");
partyName = getIntent().getStringExtra("partyName");
txtparty_Name.setText(partyName);
connectionClass = new ConnectionClass();
context=this;
selected_list.setAdapter(adapter);
try {
Connection con = connectionClass.CONN();
if (con == null) {
} else {
PreparedStatement statement = con.prepareStatement("EXEC " + pass + " " + item + " , " + mobile + "");
MyList1 = new ArrayList<DataModel>();
ResultSet rs = statement.executeQuery();
while (rs.next()) {
dataModel.setBill_date(rs.getString("bill_date"));
dataModel.setCompanyMobile(rs.getString("CompanyMobile"));
dataModel.setCity(rs.getString("city"));
dataModel.setState(rs.getString("state"));
dataModel.setShades(rs.getString("Shades"));
dataModel.setAgentMobileNumber(rs.getString("agentMobNumber"));
MyList1.add(dataModel);
dataModel=new DataModel();
adapter=new Adapter_SelectedDetail(this,search,MyList1,selected_list);
selected_list.setAdapter(adapter);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
Selected_Detail_Activity.this.adapter.getFilter().filter(s.toString());
}
});
}
}
}
catch (Exception e) {
Log.e("123", "error", e);
}
}
}
You misuse your datasets. i.e, you have erase all your original data.
firstly, you have not set backup data, replace adapters constructor with this.
public Adapter_SelectedDetail(Context context, EditText search, ArrayList MyList1, ListView listView) {
super(context,-1);
this.newList = new ArrayList<>();
this.newList.addAll(MyList1);
this.Mysearch = search;
this.listView = listView;
this.MyList = new ArrayList<>();
this.MyList.addAll(MyList1);
this.context = context;
}
and,add an override function getCount to your adapter.
#Override
public int getCount() {
return MyList.size();
}
then,
......
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<DataModel> filteredItems = new ArrayList<DataModel>();
for(int i = 0, l = newList.size(); i < l; i++)
{
DataModel dataModel = newList.get(i);
if(dataModel.getShades().toString().toLowerCase().contains(constraint))
filteredItems.add(dataModel);
}
result.count = filteredItems.size();
result.values = filteredItems;
}else
{
synchronized(this)
{
result.values = newList;
result.count = newList.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
MyList= (ArrayList<DataModel>)results.values;
notifyDataSetChanged();
}
.....
then it works fine,
Good luck.

Issue with adding addTextChangedListener in adapter

I'm trying to implement a search function in my application. I have used an adapter to because I want to display 2 textviews in listview and listview should be clickable (I don;t think it's possible to do without an adapter).
My problem is I can't use addTextChangedListener in the adapter class. it gives exception (It worked in my activity class).
search activity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_results_activity);
new SearchMenuAsyncTask(getApplicationContext(), this).execute();
listtv = (LinearLayout) findViewById(R.id.product_lv);
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text ["+s+"]");
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
final List<String> descriptions = new ArrayList<String>();
final List<String> menudescriptions = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
final JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("5")
&& (object.getString("SubCategoryID")).equals("6")
&& (object.getString("Visible")).equals("true")) {
Log.i("descriptionsBev ", object.getString("Description"));
descriptions.add(object.getString("Description"));
Log.i("MenuDescription ",
object.getString("MenuDescription"));
menudescriptions
.add(object.getString("MenuDescription"));
}
adapter = new CustomListSearch(
getApplicationContext(), descriptions,
menudescriptions);
lv.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
CustomListSearch.java
public class CustomListSearch extends BaseAdapter implements Filterable {
private Context context;
private final List<String> descriptions;
private List<String>filteredData = null;
private final List<String> menudescriptions;
private ItemFilter mFilter = new ItemFilter();
private LayoutInflater mInflater;
ArrayAdapter<String> adapter;
public CustomListSearch(Context c, List<String> data,
List<String> menudescriptions) {
this.context = c;
this.filteredData = data ;
this.descriptions = data;
this.menudescriptions = menudescriptions;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return filteredData.size();
}
#Override
public Object getItem(int position) {
return filteredData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
private TextView tvMenudescriptions;
private TextView tvDescriptions;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.search_list_item, parent, false);
holder.tvDescriptions = (TextView) convertView
.findViewById(R.id.product_name);
holder.tvMenudescriptions = (TextView) convertView
.findViewById(R.id.product_description);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvDescriptions.setText(descriptions.get(position));
holder.tvMenudescriptions.setText(menudescriptions.get(position));
LinearLayout itemlist = (LinearLayout) convertView
.findViewById(R.id.product_lv);
itemlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Still under constructions...",
Toast.LENGTH_LONG).show();
}
});
return convertView;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = descriptions;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
I was following below answer and worked this out
Custom Listview Adapter with filter Android

Android Custom Adapter Filter not working

I am using a custom adapter with a search filter in a fragment, however the results don't get filtered on a search, I debugged and stepped through my code and find that it is saying that the args.listenere = null!. What does this mean and how do I correct it? My code is below:
---------Custom Adapter -------
public class SalesPartAdapter extends BaseAdapter implements Filterable {
private ArrayList<SalesPartItem> listData;
private ArrayList<SalesPartItem> filteredData;
private SalesPartFilter filter;
private Context _context;
private LayoutInflater layoutInflater;
public SalesPartAdapter(Context context, ArrayList<SalesPartItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
_context = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
//set background colour
if (convertView == null) {
//set up holder
convertView = layoutInflater.inflate(R.layout.salespart_item, null);
holder = new ViewHolder();
holder.salesPartCodeView = (TextView) convertView.findViewById(R.id.salesPartCode);
holder.salesPartDescView = (TextView) convertView.findViewById(R.id.salesPartDescription);
holder.salesPartColourBar= (ImageView) convertView.findViewById(R.id.colourBar);
convertView.setTag(holder);
} else {
//use existing holder
holder = (ViewHolder) convertView.getTag();
}
SalesPartItem salespartView = (SalesPartItem) listData.get(position);
holder.salesPartCodeView.setText(salespartView.SalesPartCode);
holder.salesPartDescView.setText(salespartView.SalesPartDescription);
holder.salesPartColourBar.setBackgroundColor(Color.parseColor(salespartView.Colour));//String.valueOf(salespartView.Colour);
return convertView;
}
/********* holder Class to contain previously inflated xml file elements *********/
static class ViewHolder {
TextView salesPartCodeView;
TextView salesPartDescView;
ImageView salesPartColourBar;
}
public Filter getFilter() {
if (filter == null){
filter = new SalesPartFilter();
}
return filter;
}
ArrayList<SalesPartItem> filteredItems;
ArrayList<Integer>countFilteredItems;
private class SalesPartFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
filteredItems = new ArrayList<SalesPartItem>();
// countFilteredItems = new ArrayList<Integer>();
for(int i = 0, l = listData.size(); i < l; i++)
{
SalesPartItem salesPartItem = listData.get(i);
if(salesPartItem.SalesPartDescription.toString().toLowerCase().contains(constraint))
filteredItems.add(salesPartItem);
// countFilteredItems.add(i);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = listData;
result.count = listData.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
// notifyDataSetChanged();
if (results.count > 0) {
listData =(ArrayList<SalesPartItem>)results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
----------------Fragment code that deals with the list view -------------------
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//USE SAMPLE ID TO GET SALES PARTS LIST FROM DATABASE
addSalesParts.setEnabled(false);
//ListViewModel (SalesPartId,salesPartName,NotUsed)
final int numberOfAddedSalesParts = 3;
SalesPartItem sp;
// fill with some dummy data for now.
for (long i = 1; i < numberOfAddedSalesParts; i++) {
sp = new SalesPartItem();
sp.SalesPartItemId = i;
sp.SalesPartCode = "LEU" + i;
if(i!=2){
sp.SalesPartDescription = "Sales Part " + i;
}
else{
sp.SalesPartDescription = "TSalZes Part " + i;
}
sp.Colour = "#cccccc";
salesPartListViewItems.add(sp);
}
// Start of Search filtering
mListView = (ListView) getActivity().findViewById(R.id.salespartsList);
//click on item - edit order
mListView.setTextFilterEnabled(true);
//display the list via our custom adapter
mListView.setAdapter(new SalesPartAdapter(getActivity(), salesPartListViewItems);
EditText searchField = (EditText) getActivity().findViewById(R.id.typeFindSalesPart);
searchField.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
//TODO Search Lists from Database and filter accordingly
SalesPartAdapter SA = new SalesPartAdapter(getActivity(), salesPartListViewItems);
SA.getFilter().filter(s.toString());
Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
// salesPartListViewItems.contains(s);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
I have now resolved this, the issue was that I was creating a new instance of the adapter in the text watcher. Once I set it to use the adapter that created the original list then it worked fine

Android autocompletetextview to have two adapter for suggestion

I have a problem in making suggestion in AutoCompleteTextView in this pattern
[action actionFromContact] (these are 2 adapter) ex call michael (where "call" comes from action adapter , "michael" from actionFromContact adapter these following code does first it set adapter in AutoCompleteTextView to item and when text changes to call it reset to contact db from name so its like call michael ,
Problem item array is too big so I can't use replace thing , second replacing remove the first entry when second entry i.e name is been selected from drop down menu as its been replaced by space
private AutoCompleteTextView mEditText;
private TextWatcher mTextWatcher;
private ContactPickerAdapter contactPickerAdapter;
String item[] = { "Call", "Call back"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = (WithSomeOneAutoCompleteTextView) findViewById(R.id.editTextTest);
contactPickerAdapter = new ContactPickerAdapter(this,
android.R.layout.simple_dropdown_item_1line,
ContactQuery.getContacts(this, false));
mEditText.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, item));
mTextWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
String t = s.toString().replace("call ",");
contactPickerAdapter.getFilter().filter(t);
if (s.toString().equalsIgnoreCase("call ")) {
Toast.makeText(MainActivity.this, "CALL",
Toast.LENGTH_SHORT).show();
mEditText.setAdapter(contactPickerAdapter);
}
if (s.toString().equalsIgnoreCase("Call back")) {
// t.replace("call back ", "");
// System.out.println("t is: " + t);
// contactPickerAdapter.getFilter().filter(t);
Toast.makeText(MainActivity.this, "Launch",
Toast.LENGTH_SHORT).show();
}
}
};
}
This is ContactPickerAdapter
public class ContactPickerAdapter extends ArrayAdapter<Contact> implements
Filterable {
private ArrayList<Contact> contactList, cloneContactList;
private LayoutInflater layoutInflater;
private Context mContext;
public ContactPickerAdapter(Context context, int textViewResourceId,
ArrayList<Contact> contactList) {
super(context, textViewResourceId);
this.contactList = contactList;
this.cloneContactList = (ArrayList<Contact>) this.contactList.clone();
layoutInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return contactList.size();
}
#Override
public Contact getItem(int position) {
return contactList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(
R.layout.withsomeone_contact_list_item, null);
holder = new Holder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.phone = (TextView) convertView.findViewById(R.id.phone);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
Contact contact = getItem(position);
holder.name.setText(contact.contactName);
holder.phone.setText(contact.num);
return convertView;
}
#Override
public Filter getFilter() {
Filter contactFilter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results.values != null) {
contactList = (ArrayList<Contact>) results.values;
notifyDataSetChanged();
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// CharSequence t = "";
System.out.println("contraints is equal: " + constraint);
// if (constraint.toString().contains("call ")) {
// // constraint = "";
// System.out.println("contraints now: "
// + constraint.toString().replace("call ", ""));
// t = constraint.toString().replace("call ", "");
// }
// } else if
// (constraint.toString().equalsIgnoreCase("call back ")) {
// // constraint = "";
// System.out.println("contraints now: " + constraint);
// t = constraint.toString().replace("call back ", "");
//
// }
// System.out.println("clone is equal: " + t);
String sortValue = constraint == null ? "" : constraint
.toString().toLowerCase();
FilterResults filterResults = new FilterResults();
if (!TextUtils.isEmpty(sortValue.trim())) {
ArrayList<Contact> sortedContactList = new ArrayList<Contact>();
for (Contact contact : cloneContactList) {
if (contact.contactName.toLowerCase().contains(
sortValue)
|| contact.num.toLowerCase()
.contains(sortValue))
sortedContactList.add(contact);
}
filterResults.values = sortedContactList;
filterResults.count = sortedContactList.size();
}
return filterResults;
}
#Override
public CharSequence convertResultToString(Object resultValue) {
// need to save this to saved contact
return ((Contact) resultValue).contactName;
}
};
return contactFilter;
}
#SuppressWarnings("unchecked")
public void setContactList(ArrayList<Contact> contactList) {
// this isn't the efficient method
// need to improvise on this
this.contactList = contactList;
this.cloneContactList = (ArrayList<Contact>) this.contactList.clone();
notifyDataSetChanged();
}
public static class Holder {
public TextView phone, name;
}
Still a bit unclear what are you trying to achieve.
Anyway.
Well as a first step I would attach the TextWatcher to the mEditText
mEditText.addTextChangedListener(mTextWatcher);
Then I would remove
contactPickerAdapter.getFilter().filter(t);
see how it goes.
I suggest that you post the code of your contactPickerAdapter as well.

Filter ListView with arrayadapter

I'm trying to filter a listview with arrayadapter. The arraydapter parameter is a String[][]. The problem is that anything happens. I must override the Filter interface? In that case plase, can someone provide some hints?
Every position of the array I'm trying to filter is like
galleryValues[0][0] -> "tiulo"
[0][1] -> "desc"
[0][2] -> "etc"
I tryied to filter it:
lstContinente = (ListView)findViewById(R.id.list);
lstContinente.setTextFilterEnabled(true);
adapter = new PortaitArrayAdapter(cx,galleryValues);
lstContinente.setAdapter(adapter);
ed_busqueda.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
adapter.notifyDataSetChanged();
}
});
The adapter code:
public class PortaitArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[][] values;
private List<Imagen> imagenes = null;
private LayoutInflater mInflater;
public ImageLoader imageLoader;
public PortaitArrayAdapter(Context context, String[][] values) {
super(context, R.layout.gallery_row);
this.context = context;
this.values = values;
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imagenes = new ArrayList<Imagen>();
for (int i = 0; i < 20; i++) imagenes.add(new Imagen());
Bitmap def = BitmapFactory.decodeResource(this.context.getResources(),R.drawable.ic_launcher);
imageLoader=new ImageLoader(this.context,def, imagenes);
}
#Override
public int getCount (){
return this.values.length;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.gallery_row, parent, false);
holder.txtTitulo = (TextView) convertView.findViewById(R.id.txt_gallery_titulo);
holder.txtDesc = (TextView) convertView.findViewById(R.id.txt_gallery_desc);
holder.txtFecha = (TextView) convertView.findViewById(R.id.txt_gallery_fecha);
holder.txtEst = (TextView) convertView.findViewById(R.id.txt_gallery_est);
holder.imageView = (ImageView)convertView.findViewById(R.id.lst_img_gallery);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
/*LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.gallery_row, parent, false);*/
//ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
Bitmap bmp;
Log.v("Position --> ",String.valueOf(position));
try {
byte b[] = imagenes.get(position).getImageData();
if (b != null) {
bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
if (bmp != null) holder.imageView.setImageBitmap(bmp);
} else {
String urlBase = galleryValues[position][0].substring(0, galleryValues[position][0].lastIndexOf("/")+1);
String urlToEncode = galleryValues[position][0].substring(galleryValues[position][0].lastIndexOf("/")+1, galleryValues[position][0].length());
urlToEncode = URLEncoder.encode(urlToEncode,"UTF-8");
String url = urlBase.concat(urlToEncode);
url = url.replace("+", "%20");
Log.v("UrlFinal --> ",url);
imageLoader.DisplayImage(String.valueOf(position),url,act,holder.imageView, position,null);
}
} catch (Exception e) {
Log.e(this.getClass().getName(),"Exception en pos = " + position + " error:" + e.getMessage());
e.printStackTrace();
}
holder.txtTitulo.setText(galleryValues[position][1] + ", " + galleryValues[position][2]);
String[] dates = galleryValues[position][4].split("/");
String date = dates [1] + "/" + dates[0] + "/" + dates[2];
Date d1 = new Date(date);
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
holder.txtDesc.setText(galleryValues[position][3]);
holder.txtFecha.setText(df.format(d1));
holder.txtEst.setText(getText(R.string.num_fotos_gallery) + galleryValues[position][5] + " - " + getText(R.string.num_videos_gallery) + galleryValues[position][6] + " - " + getText(R.string.num_exp_gallery) + galleryValues[position][7]);
return convertView;
}
}
private static class ViewHolder {
TextView txtTitulo;
TextView txtDesc;
TextView txtFecha;
TextView txtEst;
ImageView imageView;
}
Convert your String array to ArrayList and pass it to Adapter and use below code or change below code with your String[].
You need to implement Filterable to your Adapter class and Override getFilter()
Checkout this complete example for filtering custom Adapter.
public class ListFilterActivity extends ListActivity {
private List<String> list = new ArrayList<String>();
List<String> mOriginalValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MyAdapter adapter = new MyAdapter(this, getModel());
setListAdapter(adapter);
EditText filterEditText = (EditText) findViewById(R.id.filterText);
// Add Text Change Listener to EditText
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private List<String> getModel() {
list.add("Linux");
list.add("Windows7");
list.add("Suse");
list.add("Eclipse");
list.add("Ubuntu");
list.add("Solaris");
list.add("Android");
list.add("iPhone");
list.add("Windows XP");
return list;
}
}
// Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
List<String> arrayList;
List<String> mOriginalValues; // Original Values
LayoutInflater inflater;
public MyAdapter(Context context, List<String> arrayList) {
this.arrayList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView textView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row, null);
holder.textView = (TextView) convertView
.findViewById(R.id.textview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(arrayList.get(position));
return convertView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
arrayList = (List<String>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
List<String> FilteredArrList = new ArrayList<String>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<String>(arrayList); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
String data = mOriginalValues.get(i);
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(data);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}
Here I mention the code of how We can filter the listView Data using custom Adapter
Its really help you
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
public List<AllFoodItem> allFoodItemlist;
public ArrayList<AllFoodItem> arraylist;
public ListViewAdapter(Context context, List<AllFoodItem> allFoodItemlist) {
mContext = context;
this.allFoodItemlist = allFoodItemlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<AllFoodItem>();
this.arraylist.addAll(allFoodItemlist);
}
#Override
public int getCount() {
return allFoodItemlist.size();
}
#Override
public AllFoodItem getItem(int position) {
return allFoodItemlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView foodname, quantity, calorie;
}
public View getView(final int position, View view, ViewGroup parent) {
Holder holder = new Holder();
view = inflater.inflate(R.layout.program_list, null);
// Locate the TextViews in listview_item.xml
holder.foodname = (TextView) view.findViewById(R.id.textView1);
// Set the results into TextViews holder.foodname.setText(allFoodItemlist.get(position).getName().toString());
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
allFoodItemlist.clear();
if (charText.length() == 0) {
allFoodItemlist.addAll(arraylist);
} else {
for (AllFoodItem wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
allFoodItemlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
MainActivity.java
use the ListViewAdapter class apply filter on EditText by using filter() method
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
foodname = (inputSearch.getText().toString()).trim();
// filter the data of edit Text using filter method in ListViewAdapter
String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
userGet();
// TODO Auto-generated method stub
}
});

Categories

Resources