Not able to implement search in Expandable list view - android

I am trying to implement Search filter in expandable list view.
But when I am trying to enter keyword in editText, application gets crashed.
Below are two java classes of MainActivity and ExpandableListAdapter.
MainActivity class
package com.ahmedabadjobs.dashboard;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import androidhive.dashboard.R;
import com.ahmedabadjobs.expandablelistview.ExpandableListAdapter;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
EditText inputSearch;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader,
listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// ((Filter) listAdapter.getFilter()).filter(cs);
NewsFeedActivity.this.listAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// When user changed the Text
}
});
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Company 0");
listDataHeader.add("Company 1");
listDataHeader.add("Company 2");
// Adding child data
List<String> cignex = new ArrayList<String>();
company0.add("Address Line 1");
company0.add("Address Line 2");
company0.add("Address Line 3");
company0.add("Phone number");
company0.add("Email Address");
List<String> company1 = new ArrayList<String>();
company1.add("Address Line 1");
company1.add("Address Line 2");
company1.add("Address Line 3");
company1.add("Phone number");
company1.add("Email Address");
List<String> company2 = new ArrayList<String>();
company2.add("Address Line 1");
company2.add("Address Line 2");
company2.add("Address Line 3");
company2.add("Phone number");
company2.add("Email Address");
listDataChild.put(listDataHeader.get(0), company0); // Header, Child
// data
listDataChild.put(listDataHeader.get(1), company1);
listDataChild.put(listDataHeader.get(2), company2);
}
}
ExpandableListAdapter class
package com.ahmedabadjobs.expandablelistview;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import androidhive.dashboard.R;
public class ExpandableListAdapter extends BaseExpandableListAdapter implements
Filterable {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return null;
}
}
I am getting bellow error when providing keyword in editText.
12-09 03:37:48.080: E/InputEventSender(1139): Exception dispatching finished signal.
12-09 03:37:48.080: E/MessageQueue-JNI(1139): Exception in MessageQueue callback: handleReceiveCallback
12-09 03:37:48.161: E/MessageQueue-JNI(1139): java.lang.NullPointerException
Please let me know what changes I need to make to make it functional.

use editext as follows
edit=(EditText)findViewById(R.id.editText1);
edit.addTextChangedListener(filterTextWatcher);
write a textwatcher
private TextWatcher filterTextWatcher =new TextWatcher()
{
public void beforeTextChanged(CharSequence s, int start, int count,int after)
{
}
public void onTextChanged(CharSequence s, int start, int before,int count)
{
}
public void afterTextChanged(Editable s)
{
// TODO Auto-generated method stub
((Filterable) ((ListAdapter) Adapter)).getFilter().filter(edit.getText().toString());
}
};
make a listadapter as follows
public class ListAdapter extends BaseExpandableListAdapter implements Filterable {
public void notifyDataSetInvalidated()
{
super.notifyDataSetInvalidated();
}
public Filter getFilter()
{
if(filter == null)
filter = new MangaNameFilter();
return filter;
}
a Filter class as follows
private class MangaNameFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// NOTE: this function is *always* called from a background thread, and
// not the UI thread.
constraint = edit.getText().toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
detailsList=detailsSer.GetAlldetails();
dupCatList=detailsList;
ArrayList<detailsEntity> filt = new ArrayList<detailsEntity>();
ArrayList<detailsEntity> lItems = new ArrayList<detailsEntity>();
synchronized(this)
{
lItems.addAll(dupCatList);
}
for(int i = 0, l = lItems.size(); i < l; i++)
{
detailsEntity m = lItems.get(i);
if(m.description.toLowerCase().contains(constraint))
filt.add(m);
}
result.count = filt.size();
result.values = filt;
}
else
{
detailsList=detailsSer.GetAlldetails();
dupCatList=detailsList;
synchronized(this)
{
result.count = dupCatList.size();
result.values = dupCatList;
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults result) {
// NOTE: this function is *always* called from the UI thread.
filtered = (ArrayList<detailsEntity>)result.values;
ArrayList<Integer> IdList = new ArrayList<Integer>();
IdList.clear();
for(int i=0;i<filtered.size();i++)
{
IdList.add(filtered.get(i).catID);
}
HashSet<Integer> hashSet = new HashSet<Integer>(IdList);
midList = new ArrayList<Integer>(hashSet) ;
Collections.sort(midList);
Adapter = new CategoryListAdapter(context, R.layout.list1, R.layout.list2, filtered, midList);
List.setAdapter(Adapter);
}

Here is another post that might help: ExpandableListView.OnChildClickListener
Note: This does not use editText.
I've used a search in an actionBar.
Hope this helps!

Related

How can I Pass Name & Country from Entry Item

I am developer a Apps which contain Various Name & Country List. I want to pass Employee Name & Country name to another activity on click on Child Item of Expandable ListView.
How to set On Click Listener Method on my Activity?
package nasir.main.activity;
import java.util.ArrayList;
import nasir.adapter.EntryItem;
import nasir.adapter.MyListAdapter;
import nasir.adapter.SectionItem;
import nasir.bd.poem.R;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SearchView;
public class Employee_List extends Activity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
Button Collapse;
Button Expand;
private SearchView search;
private MyListAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<SectionItem> section = new ArrayList<SectionItem>();
ArrayList<EntryItem> items = new ArrayList<EntryItem>();
ExpandableListView expandableList = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poem_list);
expandableList = (ExpandableListView) findViewById(R.id.expandableList);
Expand = (Button) findViewById(R.id.Expand);
Collapse = (Button) findViewById(R.id.Collapse);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search = (SearchView) findViewById(R.id.search);
search.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
Collapse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.collapseGroup(i);
}
Collapse.setVisibility(View.GONE);
Expand.setVisibility(View.VISIBLE);
}
});
Expand.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.expandGroup(i);
}
Expand.setVisibility(View.GONE);
Collapse.setVisibility(View.VISIBLE);
}
});
// display the list
displayList();
// expand all Groups
// expandAll();
collapseAll();
}
// method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++) {
myList.expandGroup(i);
}
}
//method to Collapse all groups
private void collapseAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.collapseGroup(i);
}
}
// method to expand all groups
private void displayList() {
// display the list
load_Part_1_Data();
// get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.expandableList);
// create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(Poem_List.this, section);
// attach the adapter to the list
myList.setAdapter(listAdapter);
myList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
int arg3, long arg4) {
// TODO Auto-generated method stub
Intent intent = new Intent(Poem_List.this, Details_Information.class);
startActivity(intent);
return false;
}
});
}
private void load_Part_1_Data() {
items = new ArrayList<EntryItem>();
section.add(new SectionItem(R.drawable.ic_launcher, "", items));
items.add(new EntryItem(R.drawable.ic_launcher, "Margerate Milan", "Computer Operator", getString(R.string.app_name)));
items.add(new EntryItem(R.drawable.ic_launcher, "Abraham Jhon", "Salse Man", getString(R.string.app_name)));
items = new ArrayList<EntryItem>();
section.add(new SectionItem(R.drawable.blank_image, "", items));
items.add(new EntryItem(R.drawable.ic_launcher, "England", "Europe", getString(R.string.app_name)));
items.add(new EntryItem(R.drawable.ic_launcher, "Japan", "Asia", getString(R.string.app_name)));
}
#Override
public boolean onClose() {
listAdapter.filterData("");
expandAll();
return true;
}
#Override
public boolean onQueryTextChange(String query) {
listAdapter.filterData(query);
expandAll();
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
listAdapter.filterData(query);
expandAll();
return false;
}
}
MyListAdapter.Class
package nasir.adapter;
import java.util.ArrayList;
import nasir.bd.poem.R;
import nasir.main.activity.Details_Information;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<SectionItem> continentList;
private ArrayList<SectionItem> originalList;
public MyListAdapter(Context context, ArrayList<SectionItem> continentList) {
this.context = context;
this.continentList = new ArrayList<SectionItem>();
this.continentList.addAll(continentList);
this.originalList = new ArrayList<SectionItem>();
this.originalList.addAll(continentList);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<EntryItem> countryList = continentList.get(groupPosition).getSectionList();
return countryList.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View view, ViewGroup parent) {
final EntryItem country = (EntryItem) getChild(groupPosition, childPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.child_row, null);
}
ImageView Rank = (ImageView) view.findViewById(R.id.Rank);
TextView Poem = (TextView) view.findViewById(R.id.Poem);
TextView Poetry = (TextView) view.findViewById(R.id.Poetry);
Rank.setImageResource(country.getRank());
Poem.setText(country.getPoem().trim());
Poetry.setText(country.getPoetry().trim());
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Details_Information.class);
Bundle bundle=new Bundle();
intent.putExtras(bundle);
intent.putExtra("header", country.getDetails_Doc());
context.startActivity(intent);
}
});
return view;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<EntryItem> countryList = continentList.get(groupPosition).getSectionList();
return countryList.size();
}
#Override
public Object getGroup(int groupPosition) {
return continentList.get(groupPosition);
}
#Override
public int getGroupCount() {
return continentList.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isLastChild, View view, ViewGroup parent) {
SectionItem continent = (SectionItem) getGroup(groupPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.group_row, null);
}
TextView heading = (TextView) view.findViewById(R.id.heading);
heading.setText(continent.getName().trim());
ImageView Group_icon = (ImageView) view.findViewById(R.id.Group_Icon);
Group_icon.setImageResource(continent.getIcon());
return view;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void filterData(String query) {
query = query.toLowerCase();
Log.v("MyListAdapter", String.valueOf(continentList.size()));
continentList.clear();
if (query.isEmpty()) {
continentList.addAll(originalList);
} else {
for (SectionItem continent : originalList) {
ArrayList<EntryItem> countryList = continent.getSectionList();
ArrayList<EntryItem> newList = new ArrayList<EntryItem>();
for (EntryItem country : countryList) {
if (country.getPoem().toLowerCase().contains(query) || country.getPoetry().toLowerCase().contains(query) ) {
newList.add(country);
}
}
if (newList.size() > 0) {
SectionItem nContinent = new SectionItem(continent.getIcon(), continent.getName(), newList);
continentList.add(nContinent);
}
}
}
Log.v("MyListAdapter", String.valueOf(continentList.size()));
notifyDataSetChanged();
}
}
In the Employee_List activity , you can access the data through index of child and group obtaining from ChildClickListener
myList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
int arg3, long arg4) {
// TODO Auto-generated method stub
//Here You can access the child data by
final EntryItem country = (EntryItem) listAdapter .getChild(arg2, arg3);
//From here you can pass the data through Intent
...
return false;
}
});

Unable to get actual position of item after filtering ListView

Here is my MainActivity.java where I define an OnClickListener on the items. Here I am always getting a wrong value of the item after filtering.
If there are 10 items in the ListView then after filtering if I get 3 items and the correct position is like 3,6,9 then I am getting 0,1,2 instead.
package com.focusmedica.maadiabetes;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
private MainAdapter adapter;
private static ListView lvFiltered;
private static ArrayList<DataModel> data=new ArrayList<>();;
MyDatabase handler;
private EditText etSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvFiltered =(ListView)findViewById(R.id.lvFiltered);
etSearch = (EditText)findViewById(R.id.etSearch);
etSearch.setText("");
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
handler=new MyDatabase(this);
data=handler.getChapterDetails();
adapter = new MainAdapter(this,data);
lvFiltered.setAdapter(adapter);
lvFiltered.setTextFilterEnabled(true);
lvFiltered.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, SubActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
if(cs.length()>0) {
etSearch.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.delete, 0);
}else{
etSearch.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
// When user changed the Text
adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
etSearch.setOnTouchListener(new View.OnTouchListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
if(etSearch.getCompoundDrawables()[2]!=null){
if(event.getX() >= (etSearch.getRight()- etSearch.getLeft() - etSearch.getCompoundDrawables()[2].getBounds().width())) {
etSearch.setText("");
}
}
}
return false;
}
});
}
}
here is Adapter class
package com.focusmedica.maadiabetes;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by windev on 8/2/2016.
*/
public class MainAdapter extends BaseAdapter implements Filterable {
ArrayList<DataModel> dataSet;
Context context;
DataModel content;
public ArrayList<DataModel> orig;
public MainAdapter(Context context, ArrayList dataSet) {
super();
this.context = context;
this.dataSet = dataSet;
}
#Override
public int getCount() {
return dataSet.size();
}
#Override
public Object getItem(int position) {
return dataSet.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
class ViewHolder {
private TextView tvChapterName;
private ImageView ivChapterIcon;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
final ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.card_layout, null);
viewHolder = new ViewHolder();
viewHolder.tvChapterName = (TextView) view.findViewById(R.id.tvChapterName);
viewHolder.ivChapterIcon=(ImageView)view.findViewById(R.id.ivChapterIcon);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
content = dataSet.get(position);
viewHolder.tvChapterName.setText(content.getChapterName());
viewHolder.ivChapterIcon.setImageResource(R.drawable.caticon);
return view;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<DataModel> results = new ArrayList<>();
final ArrayList<DataModel> ids = new ArrayList<>();
if (orig == null)
orig = dataSet;
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final DataModel g : orig) {
if (g.getChapterName().toLowerCase().contains(constraint.toString())||
g.getChapterName().toUpperCase().contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
dataSet = (ArrayList<DataModel>) results.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
To get the "old" position (which is equivalent to the item ID) for an item in the filtered list:
#Override
public long getItemId(int position) {
int itemID;
// orig will be null only if we haven't filtered yet:
if (orig == null)
{
itemID = position;
}
else
{
itemID = orig.indexOf(dataSet.get(position));
}
return itemID;
}
Now use this method with the OnItemClickListener:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, SubActivity.class);
intent.putExtra("position", adapter.getItemId(position) );
startActivity(intent);
}
Note: if you ever need to use notifyDatasetChanged() it might be a good idea to override this method as well:
#Override
public void notifyDatasetChanged()
{
// either this or: orig = dataSet;
orig = null;
super.notifyDatasetChanged();
}
After filtering the 'ArrayList' will add data from the 0th position. So you will get position as 0,1,2. You have to use id instead of position.
Store data which you want to get, in an array and retrieve data select by user using position from the same array in onClick method of listview.

How can I achieve setOnLongClickListener?

I've seen many examples of setOnLongClickListener in a ListView, but I'm using an AndroidHive's ExpandableListView, so it doesn't seem to recognized (error: setOnLongClickListener cannot be resolved to a type). How would I go about making it so that I can use setOnLongClickListener?
ExpandableListView expListView;
...
expListView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongChildClick(View v) {
return true;
}
});
MainActivity.java (listener located in first method):
package com.example.groceryrunnerv4;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;
public class MainActivity extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
//((TextView) v).setPaintFlags(((TextView) v).getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
//listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition) .setPaintFlags(CHILD.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
return false;
}
});
expListView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongChildClick(View v) {
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Adds food group data
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data groups
listDataHeader.add("Produce");
listDataHeader.add("Grains");
listDataHeader.add("Meat & Seafood");
listDataHeader.add("Frozen");
listDataHeader.add("Canned");
listDataHeader.add("Bakery");
listDataHeader.add("Beverages");
listDataHeader.add("Other");
// Adding child data items
List<String> Produce = new ArrayList<String>();
Produce.add("Chaquita Bananas");
Produce.add("Apples (8)");
Produce.add("Kiwi");
Produce.add("Romaine Lettuce (3)");
List<String> Grains = new ArrayList<String>();
Grains.add("Whole Grain Bread");
Grains.add("Whole Wheat English Muffins");
Grains.add("Pasta");
Grains.add("Oatmeal");
List<String> MeatSeafood = new ArrayList<String>();
MeatSeafood.add("My dead friends");
List<String> Frozen = new ArrayList<String>();
Frozen.add("Edamame");
Frozen.add("Bean Burgers");
List<String> Canned = new ArrayList<String>();
Canned.add("Amy's Lentils");
Canned.add("Jam");
Canned.add("Peanu Butter");
List<String> Bakery = new ArrayList<String>();
Canned.add("Fresh Bread");
List<String> Beverages = new ArrayList<String>();
Canned.add("Water");
listDataChild.put(listDataHeader.get(0), Produce);
listDataChild.put(listDataHeader.get(1), Grains);
listDataChild.put(listDataHeader.get(2), MeatSeafood);
listDataChild.put(listDataHeader.get(3), Frozen);
listDataChild.put(listDataHeader.get(4), Canned);
listDataChild.put(listDataHeader.get(5), Bakery);
listDataChild.put(listDataHeader.get(6), Beverages);
}
// Method for activity events
public void onButtonClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.CreateLG:
createLGPopup(v);
break;
case R.id.EditButton:
createEditButtonPopup(v);
break;
case R.id.SaveButton:
Toast.makeText(getApplicationContext(), "List saved.",
Toast.LENGTH_SHORT).show();
break;
case R.id.ListButton:
// chooseListDialog()
}
}
// findViewById(R.id.GetStarted).setVisibility(View.INVISIBLE);
// TextView text = (TextView) findViewById(R.id.GetStarted);
// text.setText(choice);
// CreateLG Button's Popup Menu
public void createLGPopup(View v) {
PopupMenu LGMenu = new PopupMenu(this, v);
LGMenu.getMenuInflater().inflate(R.menu.createlg_menu, LGMenu.getMenu());
LGMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String choice = new String((String) item.getTitle());
if (choice.equals("Create List")) {
createListDialog();
}
else if (choice.equals("Create Group")) {
createGroupDialog();
}
return false;
}
});
LGMenu.show();
}
// Create Edit Button's Popup Menu
public void createEditButtonPopup(View v) {
PopupMenu EditMenu = new PopupMenu(this, v);
EditMenu.getMenuInflater().inflate(R.menu.editlist_menu, EditMenu.getMenu());
EditMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String choice = new String((String) item.getTitle());
if (choice.equals("Edit List Name")) {
editListDialog();
}
else if (choice.equals("Clear All Items")) {
Toast.makeText(getApplicationContext(), "All list items deleted.",
Toast.LENGTH_SHORT).show();
}
else if (choice.equals("Delete List")) {
TextView text = (TextView) findViewById(R.id.ListName);
text.setText("Grocery Runner");
Toast.makeText(getApplicationContext(), "\"" + text.getText().toString() + "\" list edited.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
EditMenu.show();
}
// Create List Dialog
public AlertDialog.Builder dialogBuilder;
private void createListDialog() {
dialogBuilder = new AlertDialog.Builder(this);
final EditText textInput = new EditText(this);
dialogBuilder.setTitle("Create new list");
dialogBuilder.setMessage("Name your list: ");
dialogBuilder.setView(textInput);
dialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView text = (TextView) findViewById(R.id.ListName);
text.setText(textInput.getText().toString());
Toast.makeText(getApplicationContext(), "\"" + textInput.getText().toString() + "\" list created.",
Toast.LENGTH_SHORT).show();
//add list to ListsButton
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
}
});
// Output
AlertDialog dialogue = dialogBuilder.create();
dialogue.show();
}
// Create Group Dialog
private void createGroupDialog() {
dialogBuilder = new AlertDialog.Builder(this);
final EditText textInput = new EditText(this);
dialogBuilder.setTitle("Create new group");
dialogBuilder.setMessage("Name your group: ");
dialogBuilder.setView(textInput);
dialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
createGroup(textInput.getText().toString());
Toast.makeText(getApplicationContext(), "\"" + textInput.getText().toString() + "\" group created.",
Toast.LENGTH_SHORT).show();
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
}
});
// Output
AlertDialog dialogue = dialogBuilder.create();
dialogue.show();
}
public void createGroup(String inputGroup){
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data group
listDataHeader.add(inputGroup);
// Adding child data items
List<String> group = new ArrayList<String>();
Integer groupIndex = listDataHeader.indexOf(inputGroup);
listDataChild.put(listDataHeader.get(groupIndex), group);
}
// Create List Dialog
private void editListDialog() {
dialogBuilder = new AlertDialog.Builder(this);
final EditText textInput = new EditText(this);
dialogBuilder.setTitle("Edit list name");
dialogBuilder.setMessage("Name your list: ");
dialogBuilder.setView(textInput);
dialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView text = (TextView) findViewById(R.id.ListName);
text.setText(textInput.getText().toString());
Toast.makeText(getApplicationContext(), "\"" + textInput.getText().toString() + "\" list edited.",
Toast.LENGTH_SHORT).show();
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Cancelled.",
Toast.LENGTH_SHORT).show();
}
});
// Output
AlertDialog dialogue = dialogBuilder.create();
dialogue.show();
}
}
ExpandableListAdapter.java:
package com.example.groceryrunnerv4;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
getExpandableListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
int groupPosition = ExpandableListView.getPackedPositionGroup(id);
int childPosition = ExpandableListView.getPackedPositionChild(id);
// You now have everything that you would as if this was an OnChildClickListener()
// Add your logic here.
// Return true as we are handling the event.
return true;
}
return false;
}
});
from Android: long click on the child views of a ExpandableListView?

Hide Indicator For Group when group have no child in expandable listview?

i want to hide the group indicator when group have no child here i put down the code
i use the custom image for indicator expandable listview
if group have no child than indicator hide how to hide this
Home.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white" >
<RelativeLayout
android:id="#+id/header"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_alignParentTop="true"
>
<ImageView
android:id="#+id/imagemenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/menu"
android:layout_alignParentLeft="true"
/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imagemenu"
android:background="#color/ColorGray" >
<ImageView
android:id="#+id/imagemenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/bridgelogo"
android:layout_alignParentLeft="true"
/>
</RelativeLayout>
</RelativeLayout>
<ExpandableListView
android:id="#+id/expandablelistview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/header"
android:layout_above="#+id/footer"
android:indicatorRight="45sp"
android:divider="#android:color/white"
android:dividerHeight="3sp"
android:childDivider="#android:color/white"
android:groupIndicator="#drawable/selector"
>
</ExpandableListView>
<ImageView
android:id="#+id/footer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/footer"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
Selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/empty" android:state_empty="true"/>
<item android:drawable="#drawable/expand" android:state_expanded="true"/>
<item android:drawable="#drawable/empty"></item>
</selector>
HomeListActivity.java
package com.bridge.app;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.ExpandableListView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
public class HomeListActivity extends Activity
{
WebView webview;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
ArrayList<HashMap<String,String>> headerarraylist;
ArrayList<HashMap<String,String>> childarraylist;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
List<String> submenu0 = new ArrayList<String>();
List<String> submenu1 = new ArrayList<String>();
List<String> submenu2 = new ArrayList<String>();
List<String> submenu3 = new ArrayList<String>();
List<String> submenu4 = new ArrayList<String>();
List<String> submenu5 = new ArrayList<String>();
List<String> submenu6 = new ArrayList<String>();
List<String> submenu7 = new ArrayList<String>();
List<String> submenu8 = new ArrayList<String>();
List<String> submenu9 = new ArrayList<String>();
List<String> submenu10 = new ArrayList<String>();
List<String> submenu11= new ArrayList<String>();
List<String> submenu12= new ArrayList<String>();
List<String> submenu13= new ArrayList<String>();
int lastExpandedGroupPosition = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homelist);
expListView = (ExpandableListView) findViewById(R.id.expandablelistview);
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
headerarraylist=new ArrayList<HashMap<String,String>>();
childarraylist=new ArrayList<HashMap<String,String>>();
expListView.setGroupIndicator(null);
// Listview Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener()
{
#Override
public boolean onGroupClick(ExpandableListView parent, View v,int groupPosition, long id)
{
return false;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener()
{
#Override
public void onGroupExpand(int groupPosition)
{
if (groupPosition != lastExpandedGroupPosition)
{
expListView.collapseGroup(lastExpandedGroupPosition);
}
lastExpandedGroupPosition = groupPosition;
Toast.makeText(getApplicationContext(),listDataHeader.get(groupPosition) + " Expanded", Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener()
{
#Override
public void onGroupCollapse(int groupPosition)
{
Toast.makeText(getApplicationContext(),listDataHeader.get(groupPosition) + " Collapsed",Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener()
{
#Override
public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id)
{
Toast.makeText(getApplicationContext(),listDataHeader.get(groupPosition)+ " : " + listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition), Toast.LENGTH_SHORT).show();
String child=listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition);
for(int i=0;i<childarraylist.size();i++)
{
String uid=childarraylist.get(i).get(ClassVariable.SUBMENU.UID).toString();
String title=childarraylist.get(i).get(ClassVariable.SUBMENU.TITLE).toString();
String pid=childarraylist.get(i).get(ClassVariable.SUBMENU.PID).toString();
if(child.equalsIgnoreCase(title))
{
Intent intent = new Intent(HomeListActivity.this,HomeListClickActivity.class);
intent.putExtra("title", title);
intent.putExtra("uid", uid);
intent.putExtra("pid", pid);
startActivity(intent);
Log.e("Child Value uid","--------->"+uid);
Log.e("Child Value pid ","--------->"+pid);
Log.e("Child Value title","--------->"+title);
}
}
Log.e("Child Value","--------->"+child);
return false;
}
});
if (CheckConnection.getInstance(HomeListActivity.this).isOnline(HomeListActivity.this))
{
new HomeListAsynctask().execute("");
}
else
{
}
}
// Asynctask for getting the home data from url
public class HomeListAsynctask extends AsyncTask<String, List<String>,String>
{
String detail;
#Override
protected void onPreExecute()
{
}
#Override
protected String doInBackground(String... params)
{
try
{
JsonParser jparser = new JsonParser();
String menuurl="http://www.bridge.co.at/webservices/services.php?method=menu";
String menudata=jparser.getdata(menuurl);
JSONObject jobject = new JSONObject(menudata);
JSONArray jarray =jobject.getJSONArray(ClassVariable.MENU.MENU);
listDataHeader.clear();
for(int i=0;i<jarray.length();i++)
{
listDataHeader.add(jarray.getJSONObject(i).get(ClassVariable.MENU.TITLE).toString());
// For Getting Main Menu in ArrayList
String title=jarray.getJSONObject(i).get(ClassVariable.MENU.TITLE).toString();
String uid=jarray.getJSONObject(i).get(ClassVariable.MENU.UID).toString();
String pid=jarray.getJSONObject(i).get(ClassVariable.MENU.PID).toString();
HashMap<String,String> map = new HashMap<String, String>();
map.put(ClassVariable.MENU.TITLE, title);
map.put(ClassVariable.MENU.UID, uid);
map.put(ClassVariable.MENU.PID, pid);
headerarraylist.add(map);
// For Getting SubMenu in ArrayList
String submenuurl="http://www.bridge.co.at/webservices/services.php?method=submenu&uid="+uid;
String submenudata=jparser.getdata(submenuurl);
JSONObject jobjectsubmenu = new JSONObject(submenudata);
JSONArray jarraysubmenu =jobjectsubmenu.getJSONArray(ClassVariable.SUBMENU.SUBMENU);
for(int j=0;j<jarraysubmenu.length();j++)
{
String submenutitle=jarraysubmenu.getJSONObject(j).get(ClassVariable.SUBMENU.TITLE).toString();
String submenuuid=jarraysubmenu.getJSONObject(j).get(ClassVariable.SUBMENU.UID).toString();
String submenupid=jarraysubmenu.getJSONObject(j).get(ClassVariable.SUBMENU.PID).toString();
if(i==0)
{
submenu0.add(submenutitle);
}
if(i==1)
{
submenu1.add(submenutitle);
}
if(i==2)
{
submenu2.add(submenutitle);
}
if(i==3)
{
submenu3.add(submenutitle);
}
if(i==4)
{
submenu4.add(submenutitle);
}
if(i==5)
{
submenu5.add(submenutitle);
}
if(i==6)
{
submenu6.add(submenutitle);
}
if(i==7)
{
submenu7.add(submenutitle);
}
if(i==8)
{
submenu8.add(submenutitle);
}
if(i==9)
{
submenu9.add(submenutitle);
}
if(i==10)
{
submenu10.add(submenutitle);
}
if(i==11)
{
submenu11.add(submenutitle);
}
if(i==12)
{
submenu12.add(submenutitle);
}
HashMap<String,String> map1 = new HashMap<String, String>();
map1.put(ClassVariable.SUBMENU.TITLE, submenutitle);
map1.put(ClassVariable.SUBMENU.UID, submenuuid);
map1.put(ClassVariable.SUBMENU.PID, submenupid);
childarraylist.add(map1);
}
}
Log.e("Child Array List","----->"+childarraylist);
listDataChild.put(listDataHeader.get(0), submenu0); // Header, Child data
listDataChild.put(listDataHeader.get(1), submenu1);
listDataChild.put(listDataHeader.get(2), submenu2);
listDataChild.put(listDataHeader.get(3), submenu3); // Header, Child data
listDataChild.put(listDataHeader.get(4), submenu4);
listDataChild.put(listDataHeader.get(5), submenu5);
listDataChild.put(listDataHeader.get(6), submenu6); // Header, Child data
listDataChild.put(listDataHeader.get(7), submenu7);
listDataChild.put(listDataHeader.get(8), submenu8);
listDataChild.put(listDataHeader.get(9), submenu9); // Header, Child data
listDataChild.put(listDataHeader.get(10), submenu10);
listDataChild.put(listDataHeader.get(11), submenu11);
listDataChild.put(listDataHeader.get(12), submenu12); // Header, Child data
Log.e("HeaderList","---->"+listDataHeader);
Log.e("ChildList","---->"+listDataHeader);
}
catch (Exception e)
{
e.printStackTrace();
}
return detail;
}
#Override
protected void onPostExecute(String result)
{
listAdapter = new ExpandableListAdapter(HomeListActivity.this, listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
}
}
}
Expandable List Adapter.java
package com.bridge.app;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter
{
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData)
{
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon)
{
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,boolean isLastChild, View convertView, ViewGroup parent)
{
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition)
{
return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null)
{
LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView .findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
define your custom states and set them in the correct code position.
How to add a custom button state

Filter on listview disappear listitems while entering something into edittext

I am suffering a weird problem. Actually I have a customize listview in which I am using a filter, everything working fine but when I am typing a text to edittext it disappear the all listitem. I am strange why this going on with me, still I am not a champ of android so need some help. I have seen many similar problems on stackoverflow like this,this,this, and many more, but nothing works in my case. I dont know where i am doing mistake.
My listitem click working fine, So hope it will also work after item search into edittext.
Here is my MainActivity.java :
package com.sunil.listviewmuntilerowdelete;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
private String[] myfriendname = null;
EditText edtSearch;
private int[] photo = null;
ListView listView = null;
Context contex = null;
MyListAdapter adapter = null;
private List<MyFriendsSDetails> list = new ArrayList<MyFriendsSDetails>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contex = this;
listView = (ListView) findViewById(R.id.listview);
edtSearch = (EditText) findViewById(R.id.EditText01);
myfriendname = new String[] { "Sunil Gupta", "Abhishek Tripathi",
"Sandeep Pal", "Amit Verma" };
photo = new int[] { R.drawable.sunil, R.drawable.abhi,
R.drawable.sandy, R.drawable.amit };
final String text[] = { "Sunil is a great man",
"Abhishek is hardworking", "Sandeep is same as amit",
"Amit is unique" };
final Integer[] image = { R.drawable.sunil, R.drawable.abhi,
R.drawable.sandy, R.drawable.amit,
};
for (int index = 0; index < myfriendname.length; index++) {
MyFriendsSDetails details = new MyFriendsSDetails(
myfriendname[index], photo[index]);
list.add(details);
}
adapter = new MyListAdapter(contex, list);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
edtSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(MainActivity.this,
SecondActivity.class);
intent.putExtra("key1", image[position]);
intent.putExtra("key2", text[position]);
startActivity(intent);
}
});
}
}
MyListAdapter.java
package com.sunil.listviewmuntilerowdelete;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListAdapter extends ArrayAdapter<MyFriendsSDetails> {
Context context;
LayoutInflater inflater;
List<MyFriendsSDetails> list;
public MyListAdapter(Context context, List<MyFriendsSDetails> list) {
super(context, 0, list);
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, null);
holder.name = (TextView) convertView.findViewById(R.id.title);
holder.photo = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(list.get(position).getMyfriendname());
holder.photo.setImageResource(list.get(position).getPhoto());
return convertView;
}
private class ViewHolder {
TextView name;
ImageView photo;
}
}
Here is MyFriendsSDetails.java :
package com.sunil.listviewmuntilerowdelete;
public class MyFriendsSDetails {
private String myfriendname = null;
private int photo = 0;
public MyFriendsSDetails(String friendname, int myphoto) {
this.myfriendname = friendname;
this.photo = myphoto;
}
public String getMyfriendname() {
return myfriendname;
}
public void setMyfriendname(String myfriendname) {
this.myfriendname = myfriendname;
}
public int getPhoto() {
return photo;
}
public void setPhoto(int photo) {
this.photo = photo;
}
}
Thanks in advance.
As you are using custom adapter, android cant recognize "MainActivity.this.adapter.getFilter().filter(cs);"
You have to override getFilter() method and do manual changes.
Checkout below code :
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
mDisplayedValues = (ArrayList<HashMap<String, 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
ArrayList<HashMap<String, String>> FilteredArrList = new ArrayList<HashMap<String, String>>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<HashMap<String, String>>(mDisplayedValues); // 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).get("name");
if (data.toLowerCase().startsWith(constraint.toString())) {
HashMap<String, String> hmap=new HashMap<String, String>();
hmap.put("name", mOriginalValues.get(i).get("name"));
hmap.put("image", mOriginalValues.get(i).get("image"));
FilteredArrList.add(hmap);
Log.e("DEBUG", "name : "+data);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
and use it in your adapter getView()
holder.name.setText(mDisplayedValues.get(position).get("name"));

Categories

Resources