How can I Pass Name & Country from Entry Item - android

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;
}
});

Related

How to pass different intent Extras in a custom ListView in android?

here I have a String array of rootCategoryID and a String categoryID.
On my custom ListView I want to pass different IDs for each of the rows.
But I can't make it work! Here's my code:
package ir.zabardast.onlinemarket;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Main extends ListActivity {
String[] rootCategoryName = new String[6];
String[] rootCategoryImage = new String[6];
String[] rootCategoryID = new String[6];
int categoryCount;
String categoryID = "0";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(true){
setContentView(R.layout.activity_main);
HandleXML hxml = new HandleXML();
String url = "http://karakaal.com/market/category.xml";
String object = "category";
hxml.fetchXML(url, object);
while(hxml.parsingComplete);
categoryCount = hxml.getCategories().size();
for (int i = 0; i < categoryCount; i++) {
if(hxml.getCategories().get(i).getParentId() == 0){
rootCategoryName[i] = hxml.getCategories().get(i).getName();
}
}
for (int i = 0; i < categoryCount; i++) {
if(hxml.getCategories().get(i).getParentId() == 0){
rootCategoryImage[i] = hxml.getCategories().get(i).getImage();
}
}
for (int i = 0; i < categoryCount; i++) {
if(hxml.getCategories().get(i).getParentId() == 0){
rootCategoryImage[i] = hxml.getCategories().get(i).getId();
}
}
setListAdapter(new MyAdapter(this,
android.R.layout.simple_list_item_1,
R.id.listName,
rootCategoryName));
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View view, int i, long l) {
Intent intent = new Intent(Main.this, CategoryList.class);
intent.putExtra("categoryID", categoryID);
startActivity(intent);
}
});
} else if (!checkWifi()) {
setContentView(R.layout.wifi_check);
}
}
private class MyAdapter extends ArrayAdapter<String>{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] rootCategoryName) {
super(context, resource, textViewResourceId, rootCategoryName);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list, parent, false);
String[] products = rootCategoryName;
ImageView iv = (ImageView) row.findViewById(R.id.listImage);
TextView tv = (TextView) row.findViewById(R.id.listName);
tv.setText(products[position]);
int loader = R.drawable.ic_launcher;
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
String baseURL = "http://karakaal.com/market/";
imgLoader.DisplayImage(baseURL + rootCategoryImage[position], loader, iv);
categoryID = rootCategoryID[position];
return row;
}
}
#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;
}
public boolean checkWifi()
{
ConnectivityManager conman = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean wifi = conman.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
if (wifi)
return true;
else
return false;
}
}
As you can see I use a variable to set categoryID in my private class
I want to pass rootCategoryID of each row by an Intent to the next activity when each row is clicked
you can get categoryID by position of ListView clicked
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View view, int i, long l) {
Intent intent = new Intent(Main.this, CategoryList.class);
intent.putExtra("categoryID", rootCategoryID[i]);//here CategoryId
startActivity(intent);
}
});

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?

Not able to implement search in Expandable list view

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!

AlertDialog with ListView on BaseAdapter

I am getting the teams from an arraylist and show on a listview with their logos. It is working without problem. But I want to remove an item when I click long on a listview item with an yes - no alert dialog. Here is my codes and custom adapter.
package com.mesutemre.takimlarlistview;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class TakimBaseAdapter extends BaseAdapter {
Context context;
private LayoutInflater inflater = null;
private TextView lblAd, lblAciklama;
private ImageView imgTakim;
private ArrayList<Takim> items;
public TakimBaseAdapter(Context context, ArrayList<Takim> items) {
this.context = context;
this.items = items;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.activity_main, null);
lblAd = (TextView) vi.findViewById(R.id.textView1);
lblAd.setTextColor(Color.BLUE);
lblAciklama = (TextView) vi.findViewById(R.id.textViewAciklama);
imgTakim = (ImageView) vi.findViewById(R.id.takimImage);
lblAd.setText(items.get(position).getTakim_ad());
lblAciklama.setText(items.get(position).getTakim_aciklama());
int logoID = context.getResources().getIdentifier(
items.get(position).getImage(), "drawable",
context.getPackageName());
imgTakim.setImageResource(logoID);
return vi;
}
}
And I put the items of ArrayList of teams in MainActivity and it is here;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*final ArrayAdapter<Takim> adapter = new TakimAdapter(this,
R.layout.activity_main, getTakimlar());*/
final BaseAdapter adapter = new TakimBaseAdapter(MainActivity.this, getTakimlar());
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long arg3) {
Takim stakim = (Takim) parent.getItemAtPosition(position);
Toast.makeText(getBaseContext(),
"Takım : " + stakim.getTakim_ad(), Toast.LENGTH_SHORT)
.show();
}
});
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long arg3) {
final Takim stakim = (Takim) parent.getItemAtPosition(position);
// burada AlertDialog.Builder'ın constructor'ına dikkat edin.
// Listactivitymizin context'ini atıyoruz.
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Bu takımı silmek istediğinizden emin misiniz?");
builder.setPositiveButton("Evet",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
getTakimlar().remove(which);
adapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("Hayır",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
adapter.notifyDataSetChanged();
}
});
builder.show();
return false;
}
});
}
#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;
}
// Takimlar ekleniyor
private ArrayList<Takim> getTakimlar() {
ArrayList<Takim> takimList = new ArrayList<Takim>();
takimList.add(new Takim("Galatasaray", "19", "galatasaray"));
takimList.add(new Takim("Fenerbahçe", "18", "fenerbahce"));
takimList.add(new Takim("Beşiktaş", "13", "bjk"));
takimList.add(new Takim("Trabzonspor", "6", "trabzon"));
takimList.add(new Takim("Bursaspor", "1", "bursaspor"));
return takimList;
}
}
I am getting ArrayOutofBound Exception because of getTakimlar().remove(which);. How can I remove an item from my ArrayList in this situation?
Try :
if (view == null || takimList.isEmpty()) {
} else {
takimList.remove(which);
adapter.notifyDataSetChanged();
}
Use takimList.remove(which);
instead of getTakimlar().remove(which);

Android - cannot refresh ExpendableListView, it freezes

I have an ExpandableListView in which if I add some Groups during onCreate() of the activity, it's fine, but if I try to add Groups later on and then do notifyDataSetChanged() the ExpandableListView just freezes - everything else in the activity works, just the Exp.ListView hangs.
Here as you can see I add two Groups (with children) to the Exp.ListView and they function just fine. If I try to call addTeam() though it freezes/hangs.
package org.mytest;
import java.util.ArrayList;
import eigc.doubango.ScreenTeam.ScreenTeamItemGroup;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.TextView;
public class ScreenTeam extends Activity {
private TeamListAdapter mTeamListAdapter;
private ExpandableListView mTeamList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_team);
mTeamListAdapter = new TeamListAdapter(getLayoutInflater());
mTeamList = (ExpandableListView) findViewById(R.id.screen_team_teamslist);
mTeamList.setAdapter(mTeamListAdapter);
mTeamList.setGroupIndicator(null);
/* TEST */
ScreenTeamItemGroup grp1 = new ScreenTeamItemGroup("team1",1);
ScreenTeamItemChild ch1 = new ScreenTeamItemChild("child1");
ScreenTeamItemChild ch2 = new ScreenTeamItemChild("child2");
grp1.addTeamMember(ch1);
grp1.addTeamMember(ch2);
ScreenTeamItemGroup grp2 = new ScreenTeamItemGroup("team2",2);
ScreenTeamItemChild ch3 = new ScreenTeamItemChild("child1");
ScreenTeamItemChild ch4 = new ScreenTeamItemChild("child2");
ScreenTeamItemChild ch5 = new ScreenTeamItemChild("child3");
grp2.addTeamMember(ch3);
grp2.addTeamMember(ch4);
grp2.addTeamMember(ch5);
mTeamListAdapter.addTeam(grp1);
mTeamListAdapter.addTeam(grp2);
}
/*
* Callbacks
*/
/* adds a team */
public void addTeam() {
ScreenTeamItemGroup grp1 = new ScreenTeamItemGroup("team1",1);
ScreenTeamItemChild ch1 = new ScreenTeamItemChild("child1");
ScreenTeamItemChild ch2 = new ScreenTeamItemChild("child2");
grp1.addTeamMember(ch1);
grp1.addTeamMember(ch2);
mTeamListAdapter.addTeam(grp1);
mTeamListAdapter.notifyDataSetChanged();
}
/*
* Aux classes
*/
/* team group item */
static class ScreenTeamItemGroup {
final String mItemText;
final int mIconResId;
final int mTeamID;
public ArrayList<ScreenTeamItemChild> mTeamMembers;
public ScreenTeamItemGroup(String itemText, int id) {
mItemText = itemText;
mTeamID = id;
mIconResId = R.drawable.teams;
mTeamMembers = new ArrayList<ScreenTeamItemChild>();
}
public void addTeamMember(ScreenTeamItemChild member) {
if (member != null)
mTeamMembers.add(member);
}
}
/* team child item */
static class ScreenTeamItemChild {
final int mIconResId;
final String mItemText;
public ScreenTeamItemChild(String itemText) {
mIconResId = R.drawable.p2p;
mItemText = itemText;
}
}
/* handles the list of teams */
static class TeamListAdapter extends BaseExpandableListAdapter {
public ArrayList<ScreenTeamItemGroup> mTeams;
private final LayoutInflater mInflater;
public TeamListAdapter(LayoutInflater inflater) {
mInflater = inflater;
mTeams = new ArrayList<ScreenTeamItemGroup>();
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return mTeams.get(groupPosition).mTeamMembers.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
View view = convertView;
final ScreenTeamItemChild item = (ScreenTeamItemChild)getChild(groupPosition,childPosition);
if(item == null){
return null;
}
if (view == null) {
view = mInflater.inflate(R.layout.screen_team_item, null);
}
((TextView) view.findViewById(R.id.screen_team_item_text)).setText(item.mItemText);
((ImageView) view.findViewById(R.id.screen_team_item_icon)).setImageResource(item.mIconResId);
return view;
}
#Override
public int getChildrenCount(int groupPosition) {
return mTeams.get(groupPosition).mTeamMembers.size();
}
#Override
public Object getGroup(int groupPosition) {
return mTeams.get(groupPosition);
}
#Override
public int getGroupCount() {
return mTeams.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view = convertView;
final ScreenTeamItemGroup item = (ScreenTeamItemGroup)getGroup(groupPosition);
if(item == null){
return null;
}
if (view == null) {
view = mInflater.inflate(R.layout.screen_team_item, null);
}
((TextView) view.findViewById(R.id.screen_team_item_text)).setText(item.mItemText);
((ImageView) view.findViewById(R.id.screen_team_item_icon)).setImageResource(item.mIconResId);
return view;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return false;
}
public void addTeam(ScreenTeamItemGroup grp) {
if (grp != null)
mTeams.add(grp);
}
}
}
A few things:
You don't want to make your TeamListAdapter a static subclass.
Try putting the logic for adding a team into an AsyncTask as this could freeze up the UI thread.
Also, what are your logs saying?
I solved this by using runOnUiThread in my addTeam() instead and it worked flawlessly.

Categories

Resources