AutoCompleteTextView didnt work - android

now i am using autocompleteTextview for showing suggestion , i get the data from webservice and and i set the adapter.
i dont get an error but when i click the Textview it wont show anything.and then I check the list and its contains the data.
am i doing a mistake here ?
here is my code
<AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/acCustomer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/etCustomerOther"
android:layout_marginBottom="10dp"
android:layout_alignLeft="#+id/spCustomer"/>
--class--
private static List<String> customerList;
private class LoadCustomer extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
pBar.setVisibility(View.VISIBLE);
pBar.setIndeterminate(false);
pBar.setClickable(false);
}
#Override
protected Void doInBackground(Void... params) {
try {
RESTClient client = new RESTClient(URLService+"get?method=getallcustomerlist&value=");
client.Execute(RESTClient.RequestMethod.GET);
responseCustomer = client.getResponse();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
try{
responseCustomer = responseCustomer.replace("\\\"","\"");
responseCustomer = responseCustomer.substring(1, responseCustomer.length() - 1);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(responseCustomer);
String Status = jsonObject.get("Status").toString();
if (Status == "true"){
// JSONArray structure = (JSONArray) jsonObject.get("DataList");
String dataku = jsonObject.get("DataList").toString();
try {
dataku = CRYYPT.decrypt(Enc_Pass, dataku);
}catch (GeneralSecurityException e){
//handle error - could be due to incorrect password or tampered encryptedMsg
}
JSONParser parser = new JSONParser();
JSONArray structure = (JSONArray) parser.parse(dataku);
customerList = new ArrayList<String>();
customerList.add("--Choose--");
for (int i = 0; i < structure.size(); i++) {
JSONObject customerlist = (JSONObject) structure.get(i);
customerList.add(customerlist.get("CustomerName").toString());
}
customerList.add("Other");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(WorkflowActivity.this, android.R.layout.simple_list_item_1, customerList);
acCustomer.setAdapter(adapter);
}else {
}
}
catch(Exception e)
{
e.printStackTrace();
}
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
pBar.setClickable(true);
pBar.setVisibility(View.GONE);
}
}
--List Customer Item--
public class ListCustomerItem {
public String CustName;
/*public String CustLocation;
public String CustID;*/
}
--List Customer Adapter--
public class ListCustomerAdapter extends ArrayAdapter<ListCustomerItem> {
public ListCustomerAdapter(Context context, List<ListCustomerItem> items)
{
super(context, R.layout.style_fragment_list_customer, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.style_fragment_list_customer, parent, false);
// initialize the view holder
viewHolder = new ViewHolder();
viewHolder.tvCustName = (TextView) convertView.findViewById(R.id.tvCustName);
// viewHolder.tvCustLocation = (TextView) convertView.findViewById(R.id.tvCustLocation);
convertView.setTag(viewHolder);
} else {
// recycle the already inflated view
viewHolder = (ViewHolder) convertView.getTag();
}
// update the item view
ListCustomerItem item = getItem(position);
viewHolder.tvCustName.setText(item.CustName);
// viewHolder.tvCustLocation.setText(item.CustLocation);
return convertView;
}
private static class ViewHolder {
TextView tvCustName;
TextView tvCustLocation;
}
}

Have you tried using android:completionThreshold="1" inside AutoCompleteTextView?
or called mAutoCompleteTextView.setThreshold(1) to AutoCompleteTextView reference?

mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
Set your AutoCompleteTextView with Custom Adapter
mAutoCompleteTextView.setSelection(0);
mCustomAutoFilterAdapter = new CustomAutoFilterAdapter(this,R.layout.spinner_row, yourList);
mAutoCompleteTextView.setThreshold(1);
mAutoCompleteTextView.setAdapter(mCustomAutoFilterAdapter);
In your Custom Adapter Class include
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(viewResourceId, null);
}
return v;
}
#Override
public Filter getFilter() {
return nameFilter;
}
Filter nameFilter = new Filter() {
#Override
public String convertResultToString(Object resultValue) {
String str = "get your values from resultValue";
return str;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if(constraint != null) {
suggestions.clear();
"DO your Activities"
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
"Do your Activities here"
}
};

Related

searchview for multicolum listview

I am using a ListViewAdapter which extends ArrayAdapter to display results in ListView. I have 3 TextView in the ListView to display the output. I want to implement a searchview but when I type in search bar the screen goes blank. How do I implement it? I tried with addTextChangedListener using EditText also but no output.This is Activity
searchView = (SearchView)findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
}
private void loadDescriptionList() {
final ProgressDialog progressDialog = new ProgressDialog(TestDetails.this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
progressDialog.dismiss();
try {
JSONObject obj = new JSONObject(response);
JSONArray heroArray = obj.getJSONArray("list");
for (int i = 0; i < heroArray.length(); i++) {
JSONObject heroObject = heroArray.getJSONObject(i);
TDescription hero = new TDescription(heroObject.getString("test_code"), heroObject.getString("test_description"),heroObject.getString("test_price"));
heroList.add(hero);
}
adapter = new ListViewAdapter(heroList, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
progressDialog.dismiss();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
LISTVIEWADAPTER.JAVA
public class ListViewAdapter extends ArrayAdapter<TDescription> {
private List<TDescription> heroList;
private Context mCtx;
Typeface typeface;
TextView rup;
public ListViewAdapter(List<TDescription> heroList, Context mCtx) {
super(mCtx, R.layout.list_items, heroList);
this.heroList = heroList;
this.mCtx = mCtx;
typeface = Typeface.createFromAsset(mCtx.getAssets(), "fontawesome-webfont.ttf");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View listViewItem = inflater.inflate(R.layout.list_items, null, true);
TextView code = (TextView)listViewItem.findViewById(R.id.code);
TextView desc = (TextView)listViewItem.findViewById(R.id.desc);
TextView price = (TextView)listViewItem.findViewById(R.id.price);
rup = (TextView)listViewItem.findViewById(R.id.rupee);
rup.setTypeface(typeface);
TDescription hero = heroList.get(position);
code.setText(hero.getCode());
desc.setText(hero.getDesc());
price.setText(hero.getPrice());
return listViewItem;
}
}
enter image [description]1 here
You have to implement filterable interface to get your result just change your listview adapter class to below code
public class ListViewAdapter extends ArrayAdapter<TDescription> implements Filterable {
private List<TDescription> heroList;
private List<TDescription> mFilterData;
private Context mCtx;
private ItemFilter mFilter = new ItemFilter();
private TextView rup;
public ListViewAdapter(List<TDescription> heroList, Context mCtx) {
super(mCtx, R.layout.list_items, heroList);
this.heroList = heroList;
this.mFilterData = heroList;
this.mCtx = mCtx;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View listViewItem = inflater.inflate(R.layout.list_items, null, true);
TextView code = (TextView) listViewItem.findViewById(R.id.code);
TextView desc = (TextView) listViewItem.findViewById(R.id.desc);
TextView price = (TextView) listViewItem.findViewById(R.id.price);
rup = (TextView) listViewItem.findViewById(R.id.rupee);
TDescription hero = mFilterData.get(position);
code.setText(hero.getCode());
desc.setText(hero.getDesc());
price.setText(hero.getPrice());
return listViewItem;
}
public int getCount() {
return mFilterData.size();
}
public TDescription getItem(int position) {
return mFilterData.get(position);
}
public long getItemId(int position) {
return position;
}
#NonNull
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String userString = constraint.toString().toLowerCase();
FilterResults filterResults = new FilterResults();
final List<TDescription> originalList = heroList;
int count = originalList.size();
final ArrayList<TDescription> resultList = new ArrayList<>(count);
TDescription tDescription;
for (int i = 0; i < count; i++) {
tDescription = originalList.get(i);
if (tDescription.getDesc().toLowerCase().contains(userString)) {
resultList.add(tDescription);
}
}
filterResults.values = resultList;
filterResults.count = resultList.size();
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mFilterData = (ArrayList<TDescription>) results.values;
notifyDataSetChanged();
}
}
}
it will filter the data based on your description

android SimpleSectionAdapter from adapter displaying empty list

i really need help debugging this android app i am building. I have a custom adapter. when i dont use it with simpleSectionAdapter it displays list items correctly, but when i use SimpleSectionAdapter from adapter kit, it displays blank list. I want to have sections in my list according to names. Thanks in advance.
Heres's my adapter
public class CustomContriAdapter extends BaseAdapter implements Filterable{
List<Contributions> contributions;
LayoutInflater inflater;
Context context;
public List<Contributions> orig;
public CustomContriAdapter(Context context, List<Contributions> contributions) {
this.contributions = contributions;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return contributions.size();
}
#Override
public Object getItem(int position) {
return contributions.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final List<Contributions> results = new ArrayList<Contributions>();
if (orig == null)
orig = contributions;
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final Contributions g : orig) {
if (g.getContributor_name().toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
Filter.FilterResults results) {
contributions = (ArrayList<Contributions>) results.values;
notifyDataSetChanged();
}
};
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.contri_list_item_layout, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
Contributions currentListData = (Contributions) getItem(position);
mViewHolder.tvTitleName.setText(currentListData.getContributor_name());
//date created at
Date createdAt = currentListData.getCreated();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String createdDate = df.format(createdAt);
mViewHolder.tvDescDate.setText(createdDate);
return convertView;
}
private class MyViewHolder {
TextView tvTitleName, tvDescDate;
public MyViewHolder(View item) {
tvTitleName = (TextView) item.findViewById(R.id.name_view);
tvDescDate = (TextView) item.findViewById(R.id.contri_created_date);
}
}
}
here's how am calling it in the onCreate()
Collections.sort(allContributions, new Comparator<Contributions>() {
#Override
public int compare(Contributions lhs, Contributions rhs) {
return lhs.getContributor_name().compareTo(rhs.getContributor_name());
}
});
InstantAdapter<Contributions> contribu = new InstantAdapter<Contributions>(
this,R.layout.contri_list_item_layout, Contributions.class, allContributions);
//wrap adapter to simple section adapter
SimpleSectionAdapter<Contributions> sectionAdapter = new SimpleSectionAdapter<Contributions>(
this, contribu, R.layout.section_header, R.id.section_text , new ContributionsSectionizer());
listView.setAdapter(sectionAdapter);
here's the sectionizer,
public class ContributionsSectionizer implements Sectionizer<Contributions> {
#Override
public String getSectionTitleForItem(Contributions contributions) {
return contributions.getContributor_name();
}
}
and the items
protected List<Contributions> allContributions = new ArrayList<>();

How to create custom BaseAdapter for AutoCompleteTextView

I've been having difficulty creating a custom ArrayAdapter for AutoCompleteTextView such errors that would come up despite following code found on the internet would be:
Dropdown would not appear.
Custom Objects and their details would not appear.
So for those who are having or had the same problem as me, I recommend using BaseAdapter for AutoCompleteTextView instead.
The following is my working code using ArrayAdapter.
Let's assume the reponse data from web service looks like the following:
[
{
"id": "1",
"name": "Information Technology"
},
{
"id": "2",
"name": "Human Resources"
},
{
"id": "3",
"name": "Marketing and PR"
},
{
"id": "4",
"name": "Research and Developement"
}
]
Then in your Android client:
Department class:
public class Department {
public int id;
public String name;
}
Custom Adapter class:
public class DepartmentArrayAdapter extends ArrayAdapter<Department> {
private final Context mContext;
private final List<Department> mDepartments;
private final List<Department> mDepartmentsAll;
private final int mLayoutResourceId;
public DepartmentArrayAdapter(Context context, int resource, List<Department> departments) {
super(context, resource, departments);
this.mContext = context;
this.mLayoutResourceId = resource;
this.mDepartments = new ArrayList<>(departments);
this.mDepartmentsAll = new ArrayList<>(departments);
}
public int getCount() {
return mDepartments.size();
}
public Department getItem(int position) {
return mDepartments.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
if (convertView == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(mLayoutResourceId, parent, false);
}
Department department = getItem(position);
TextView name = (TextView) convertView.findViewById(R.id.textView);
name.setText(department.name);
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
public String convertResultToString(Object resultValue) {
return ((Department) resultValue).name;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
List<Department> departmentsSuggestion = new ArrayList<>();
if (constraint != null) {
for (Department department : mDepartmentsAll) {
if (department.name.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
departmentsSuggestion.add(department);
}
}
filterResults.values = departmentsSuggestion;
filterResults.count = departmentsSuggestion.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mDepartments.clear();
if (results != null && results.count > 0) {
// avoids unchecked cast warning when using mDepartments.addAll((ArrayList<Department>) results.values);
for (Object object : (List<?>) results.values) {
if (object instanceof Department) {
mDepartments.add((Department) object);
}
}
notifyDataSetChanged();
} else if (constraint == null) {
// no filter, add entire original list back in
mDepartments.addAll(mDepartmentsAll);
notifyDataSetInvalidated();
}
}
};
}
}
Main Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
mAutoCompleteTextView.setThreshold(1);
new DepartmentRequest().execute();
}
private class DepartmentRequest extends AsyncTask<Void, Void, JSONArray> {
#Override
protected JSONArray doInBackground(Void... voids) {
OkHttpJsonArrayRequest request = new OkHttpJsonArrayRequest();
try {
return request.get("http://...");
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
super.onPostExecute(jsonArray);
if (jsonArray != null && jsonArray.length() > 0) {
Gson gson = new Gson();
Department[] departments = gson.fromJson(jsonArray.toString(), Department[].class);
mDepartmentList = Arrays.asList(departments);
mDepartmentArrayAdapter = new DepartmentArrayAdapter(mContext, R.layout.simple_text_view, mDepartmentList);
mAutoCompleteTextView.setAdapter(mDepartmentArrayAdapter);
}
}
}
private class OkHttpJsonArrayRequest {
OkHttpClient client = new OkHttpClient();
// HTTP GET REQUEST
JSONArray get(String url) throws IOException, JSONException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return new JSONArray(response.body().string());
}
}
Here's the screenshot:
Hope this helps!
Custom BaseAdapter Class
public class ObjectAdapter extends BaseAdapter implements Filterable {
private Context context;
private ArrayList<Object> originalList;
private ArrayList<Object> suggestions = new ArrayList<>();
private Filter filter = new CustomFilter();
/**
* #param context Context
* #param originalList Original list used to compare in constraints.
*/
public ObjectAdapter(Context context, ArrayList<Object> originalList) {
this.context = context;
this.originalList = originalList;
}
#Override
public int getCount() {
return suggestions.size(); // Return the size of the suggestions list.
}
#Override
public Object getItem(int position) {
return suggestions.get(position).getCountryName();
}
#Override
public long getItemId(int position) {
return 0;
}
/**
* This is where you inflate the layout and also where you set what you want to display.
* Here we also implement a View Holder in order to recycle the views.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.adapter_autotext,
parent,
false);
holder = new ViewHolder();
holder.autoText = (TextView) convertView.findViewById(R.id.autoText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.autoText.setText(suggestions.get(position).getCountryName());
return convertView;
}
#Override
public Filter getFilter() {
return filter;
}
private static class ViewHolder {
TextView autoText;
}
/**
* Our Custom Filter Class.
*/
private class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
suggestions.clear();
if (originalList != null && constraint != null) { // Check if the Original List and Constraint aren't null.
for (int i = 0; i < originalList.size(); i++) {
if (originalList.get(i).getCountryName().toLowerCase().contains(constraint)) { // Compare item in original list if it contains constraints.
suggestions.add(originalList.get(i)); // If TRUE add item in Suggestions.
}
}
}
FilterResults results = new FilterResults(); // Create new Filter Results and return this to publishResults;
results.values = suggestions;
results.count = suggestions.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
Main Activity Class
public class MainActivity extends AppCompatActivity{
private SGetCountryListAdapter countryAdapter;
private ArrayList<SGetCountryList> countryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
country = (AutoCompleteTextView) findViewById(R.id.country);
countryAdapter = new SGetCountryListAdapter(getApplicationContext(),
ConnectionParser.SGetCountryList);
country.setAdapter(countryAdapter);
country.setThreshold(1);
}
}
Drop down layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/autoText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:textColor="#color/black" />
</LinearLayout>
My Original List has data taken from web service so let's just assume that it already has data. Of course you can customize the dropdown even more by adding more views, just don't forget to update the adapter in order to incorporate the new views.

Loading the filtered items to search output

I have implement search for my application. For that I have used an adapter as well. I have loaded 30 items to the search screen. When I pressed letter z to search, then letter z belongs to 4 items out of 30 items in the list.
According to the below shown code it identifies the number 4 and shows the first 4 items out of the 30 items. When I debug inside getFilter(), it shows the filtered items correctly(I have provided a screen shot).
My problem is how can I load the filtered items. Bit confused here.
search.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);
lv.setTextFilterEnabled(true);
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());
TextView headerTV = (TextView) findViewById(R.id.search_header);
headerTV.setText("SEARCH RESULTS");
}
#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> menudescriptions = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
final JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")
&& (object.getString("Visible")).equals("true")) {
Log.i("descriptionsTop ", 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;
List<String> descriptions;
private List<String>filteredDescriptions;
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.filteredDescriptions = data ;
this.descriptions = data;
this.menudescriptions = menudescriptions;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return filteredDescriptions.size();
}
#Override
public Object getItem(int position) {
return filteredDescriptions.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) {
filteredDescriptions = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
Screen shot
To filter adapter that contains list of custom object
Create a Object:
public class TvObject {
String name;
String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
After:
public class CustomListSearch extends BaseAdapter implements Filterable {
private Context context;
private ItemFilter mFilter = new ItemFilter();
private LayoutInflater mInflater;
private List<TvObject> mListTvObject = new ArrayList<>();
private List<TvObject> mListTvObjectFiltered = new ArrayList<>();
public CustomListSearch(Context c, List<TvObject> mListTvObject) {
this.context = c;
mInflater = LayoutInflater.from(context);
this.mListTvObject = mListTvObject;
this.mListTvObjectFiltered = mListTvObject;
}
#Override
public int getCount() {
return mListTvObjectFiltered.size();
}
#Override
public Object getItem(int position) {
return mListTvObjectFiltered.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 = mInflater.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(mListTvObjectFiltered.get(position).getName());
holder.tvMenudescriptions.setText(mListTvObjectFiltered.get(position).getDescription());
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() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
int count = mListTvObject.size();
final ArrayList<TvObject> mListResult = new ArrayList<>();
String name;
for (int i = 0; i < count; i++) {
TvObject mTvObject = mListTvObject.get(i);
name = mTvObject.getName();
if (name.toLowerCase().contains(filterString)) {
mListResult.add(mTvObject);
}
}
results.values = mListResult;
results.count = mListResult.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
mListTvObjectFiltered = (ArrayList<TvObject>) results.values;
notifyDataSetChanged();
}
}
}
Edited:
In your Activity do something like this!
try {
final List<TvObject > mListObjects = new ArrayList<>();
for (int i = 0; i < responseJson.length(); ++i) {
final JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")
&& (object.getString("Visible")).equals("true")) {
Log.i("descriptionsTop ", object.getString("Description"));
Log.i("MenuDescription ", object.getString("MenuDescription"));
TvObject mTvObject = new TvObject();
mTvObject.setName(object.getString("Description"));
mTvObject.setDescription(object.getString("MenuDescription"));
mListObjects.add(mTvObject);
}
adapter = new CustomListSearch( getApplicationContext(), mListObjects);
lv.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}

android-notifyDataSetChanged doesn't work on BaseAdapter

i've a listview on my activity , when I reach the end of listview , it calls async and it getting new data using json .
this is the async and baseAdaper codes :
ListAdapter ladap;
private class GetContacts AsyncTask<Void, Void,ArrayList<HashMap<String, String>>> {
#Override
protected Void doInBackground(Void... arg0) {
Spots_tab1_json sh = new Spots_tab1_json();
String jsonStr = sh.makeServiceCall(url + page, Spots_tab1_json.GET);
ArrayList<HashMap<String, String>> dataC = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8");
String dates = new String(c.getString("dates").getBytes("ISO-8859-1"), "UTF-8");
String price = new String(c.getString("gheymat").getBytes("ISO-8859-1"), "UTF-8");
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("id", id);
contact.put("dates", dates);
contact.put("price", price);
dataC.add(contact);
}
}
} catch (JSONException e) {
goterr = true;
} catch (UnsupportedEncodingException e) {
goterr = true;
}
} else {
goterr = true;
}
return dataC;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if (!isCancelled() && goterr == false) {
if(ladap==null){
ladap=new ListAdapter(MainActivity.this,result);
lv.setAdapter(ladap);
}else{
ladap.addAll(result);
ladap.notifyDataSetChanged();
}
}
}
public class ListAdapter extends BaseAdapter {
Activity activity;
public ArrayList<HashMap<String, String>> list;
public ListAdapter(Activity activity,ArrayList<HashMap<String, String>> list) {
super();
this.activity = (Activity) activity;
this.list = list;
}
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
public int getCount() {
return contactList.size();
}
public Object getItem(int position) {
return contactList.get(position);
}
public long getItemId(int arg0) {
return 0;
}
private class ViewHolder {
TextView title,price;
ImageView img ;
//RelativeLayout rl;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.price = (TextView) convertView.findViewById(R.id.price);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
item = contactList.get(position);
holder.price.setText(item.get("price"));
return convertView;
}
}
I logged here , when I reach the end of listView , it calls addAll and it returns new 30 items buy it doesn't added to listview , I don't know why .
First of all you have already notify your list view when you call addAll() so this code no longer required please remove from your code :
ladap.notifyDataSetChanged();
Add new data to list view data holder instead of assign new data to list view data holder :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
Replace with :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
if(list==null){
list = new ArrayList<HashMap<String, String>>();
}
list.addAll(result)
notifyDataSetChanged();
}
Try to change this :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
To :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
for(int i = 0;i < result.size(); i++)
list.add(result.get(i));
//notifyDataSetChanged(); //no need to call again here
}
The point is, i think this.list = result; will delete the old items before adding a new item.

Categories

Resources