How can I achieve setOnLongClickListener? - android

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?

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

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!

BaseExpandableListAdapter notifyDataSetChanged() error

I looked through a lot of information, but have not found the right solution.
My code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
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.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
MyPointsDB db;
ArrayList<String> arr_book_title = new ArrayList<String>();
ArrayList<String> arr_book_href = new ArrayList<String>();
String selGroupParam;
String selItemParam;
public static String PACKAGE_NAME;
File directory;
String directory_string;
private Context _context;
private List<String> _listDataHeader; // header titles
private List<String> _paramDataHeader;
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private List<String> _paramDataChild;
AlertDialog dialog;
public ExpandableListAdapter(Context context, List<String> listDataHeader, List<String> paramDataHeader, HashMap<String, List<String>> listChildData, List<String> paramChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._paramDataHeader = paramDataHeader;
this._listDataChild = listChildData;
this._paramDataChild = paramChildData;
//PACKAGE_NAME = _context.getPackageName();
this.db = new MyPointsDB(_context);
}
#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;
}
public String getChildParam(int groupPosition, int childPosition) {
return _paramDataChild.get(childPosition).toString();
}
#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.setTag(_paramDataChild.get(childPosition).toString());
txtListChild.setText(childText);
Button btnItem = (Button) convertView.findViewById(R.id.iconShowParamItem);
btnItem.setTag(_paramDataChild.get(childPosition).toString());
btnItem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
selItemParam = view.getTag().toString().trim();
final CharSequence[] items = {_context.getString(R.string.operation_del_book)};
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String[] separated = selItemParam.split(";");
String url_base = separated[1];
// Delete book
if (items[item] == _context.getString(R.string.operation_del_book)) {
new AlertDialog.Builder(_context)
.setTitle(R.string.alert_del_book_caption)
.setMessage(R.string.alert_del_book_message)
.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] separated = selItemParam.split(";");
String _id = separated[0];
db.deleteBOOKid(_id);
//Toast.makeText(_context, selItemParam, Toast.LENGTH_LONG).show();
//refreshList();
//Toast.makeText(_context, _context.getString(R.string.operation_del_book), Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.button_cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
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);
Button btnGroup = (Button) convertView.findViewById(R.id.iconShowParamGroup);
btnGroup.setTag(_paramDataHeader.get(groupPosition).toString());
btnGroup.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(_context, "btnGroup", Toast.LENGTH_SHORT).show();
selGroupParam = view.getTag().toString().trim();
final CharSequence[] items = {_context.getString(R.string.operation_add_book), _context.getString(R.string.operation_del_autor)};
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//Toast.makeText(_context, items[item], Toast.LENGTH_SHORT).show();
String[] separated = selGroupParam.split(";");
String url_base = separated[1];
// Add book
if (items[item] == _context.getString(R.string.operation_add_book)) {
new selectBookInAutor().execute(url_base);
}
// Delete book
if (items[item] == _context.getString(R.string.operation_del_autor)) {
new AlertDialog.Builder(_context)
.setTitle(R.string.alert_del_autor_caption)
.setMessage(R.string.alert_del_autor_message)
.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] separated = selGroupParam.split(";");
String _id = separated[0];
db.deleteAUTORid(_id);
notifyDataSetChanged();
}
})
.setNegativeButton(R.string.button_cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private class selectBookInAutor extends AsyncTask<String, Void, String> {
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
arr_book_title.clear();
arr_book_href.clear();
mProgressDialog = new ProgressDialog(_context);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
StringBuilder sb = new StringBuilder();
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
//Elements links = doc.select("dl>dl>dt>li>a");
Elements links = doc.select("li>a");
for (Element link : links) {
sb.append(link.text());
arr_book_title.add(link.text());
arr_book_href.add(Jsoup.clean(link.attr("abs:href"), Whitelist.basic()));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
//Toast.makeText(_context, result, Toast.LENGTH_LONG).show();
final CharSequence[] items = arr_book_title.toArray(new CharSequence[arr_book_title.size()]);
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setTitle("Select The Difficulty Level");
builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
seletedItems.add(indexSelected);
}else if(seletedItems.contains(indexSelected)){
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Toast.makeText(_context, seletedItems.toString(), Toast.LENGTH_SHORT).show();
for (Object s : seletedItems){
String[] separated = selGroupParam.split(";");
String _idautor = separated[0].toString();
long id_book = db.insertBOOK(_idautor, arr_book_href.get(Integer.valueOf(s.toString())).toString(), "", arr_book_title.get(Integer.valueOf(s.toString())).toString());
new saveBookInAutor().execute(arr_book_href.get(Integer.valueOf(s.toString())).toString(), _idautor, String.valueOf(id_book));
}
//refreshList();
}
}).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
}).create().show();
}else{
Toast.makeText(_context, "Error get book autor", Toast.LENGTH_SHORT).show();
}
mProgressDialog.dismiss();
}
}
private class saveBookInAutor extends AsyncTask<String, Void, String> {
ProgressDialog mProgressDialog2;
String _idautor = "", _idbook = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog2 = new ProgressDialog(_context);
mProgressDialog2.setMessage("Save page...");
mProgressDialog2.setIndeterminate(false);
mProgressDialog2.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
String _html = "";
_idautor = params[1];
_idbook = params[2];
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
_html = doc.select("dd").outerHtml();
} catch (IOException e) {
e.printStackTrace();
}
return Jsoup.clean(_html, Whitelist.basic());
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
Toast.makeText(_context, "Save file", Toast.LENGTH_SHORT).show();
String html = "<html lang='ru'><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head><body>"+result+"</body></html>";
//String html = result;
savePageToFile(_idautor + "_" + String.valueOf(_idbook), html);
}else{
Toast.makeText(_context, "Error save page", Toast.LENGTH_SHORT).show();
}
mProgressDialog2.dismiss();
}
}
public void refreshList() {
Intent intent = new Intent(_context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
_context.startActivity(intent);
}
public void savePageToFile(String filename, String html) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(_context.openFileOutput(filename, Context.MODE_PRIVATE));
outputStreamWriter.write(html);
outputStreamWriter.close();
}
catch (IOException e) {
//Log.e("Exception", "File write failed: " + e.toString());
}
}
public String readPageFile(String filename) {
String ret = "";
try {
InputStream inputStream = _context.openFileInput(filename);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
//Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
//Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
}
Problem is Delete book. After removal of the book from the database I want to update the screen ExpandableListView. This error occurs when you call the notifyDataSetChanged(). The element does not disappears from the screen.
I found a crutch to solve the problem:
Intent intent = new Intent(_context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
_context.startActivity(intent);
But this is not entirely correct.
I ask your help.
You delete the item from the database, but it is still present in the lists that you have. You have to update the _listDataHeader list after you delete the item, and then notifyDataSetChanged. Also you should remove the child which corresponds to this item. Since you have many lists, update them also when an item is deleted.
.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] separated = selItemParam.split(";");
String _id = separated[0];
db.deleteBOOKid(_id);
//update lists here, and remove the header, child items and anything related..
// _listDataHeader.remove(groupPosition) // groupPosition should be final
// etc. etc.
notifyDataSetChanged();
} })
To ensure that data is consistent, when you delete something.. delete other related items too.. for example:
if _paramDataChild and _paramDataHeader are related to the item being deleted, you may want to update them too.. so that they don't have values which relate to the deleted item. (this depends on your scenario, i am just giving an example)

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

when scroll up & down in expandable list views get change

Im using an expandable list in my app,my question is when i scroll up and down in the list, views get changed, please let me know how to fix this
Thanks,
Sam.
below is the code
package com.test.android;
import java.util.ArrayList;
import java.util.Random;
import android.app.ExpandableListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.TextView;
/**
* Demonstrates expandable lists using a custom {#link ExpandableListAdapter}
* from {#link BaseExpandableListAdapter}.
*/
public class ExpandableList1 extends ExpandableListActivity {
MyExpandableListAdapter mAdapter;
ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up our adapter
mAdapter = new MyExpandableListAdapter(this);
setListAdapter(mAdapter);
}
/**
* A simple adapter which maintains an ArrayList of photo resource Ids.
* Each photo is displayed as an image. This adapter supports clearing the
* list of photos and adding a new photo.
*
*/
private Handler actionhandler = new Handler(){
/* (non-Javadoc)
* #see android.os.Handler#handleMessage(android.os.Message)
*/
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
mAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
};
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
private ArrayList<String> groups = new ArrayList<String>();
private ArrayList<ArrayList<String>> children = new ArrayList<ArrayList<String>>();
private Context context;
public MyExpandableListAdapter(Context context) {
super();
this.context = context;
groups.add("People Names");
groups.add("Dog Names");
groups.add("Cat Names");
groups.add("Fish Names");
ArrayList<String> child1 = new ArrayList<String>();
child1.add("Arnold-1");
child1.add("Barry-2");
child1.add("Chuck-3");
child1.add("David-4");
child1.add("Arnold-5");
child1.add("Barry-6");
child1.add("Chuck-7");
child1.add("David-8");
child1.add("Arnold-9");
child1.add("Barry-10");
child1.add("Chuck-11");
child1.add("David-12");
child1.add("Arnold-13");
child1.add("Barry-14");
child1.add("Chuck-15");
child1.add("David-16");
children.add(child1);
ArrayList<String> child2 = new ArrayList<String>();
child2.add("Ace-17");
child2.add("Bandit-18");
child2.add("Cha-Cha-19");
child2.add("Deuce-20");
children.add(child2);
ArrayList<String> child3 = new ArrayList<String>();
child3.add("Fluffy-21");
child3.add("Snuggles-22");
child3.add("Fluffy-23");
child3.add("Snuggles-24");
child3.add("Fluffy-25");
child3.add("Snuggles-26");
child3.add("Fluffy-27");
child3.add("Snuggles-28");
child3.add("Fluffy-29");
child3.add("Snuggles-30");
child3.add("Fluffy-31");
child3.add("Snuggles-32");
child3.add("Fluffy-33");
child3.add("Snuggles-34");
children.add(child3);
ArrayList<String> child4 = new ArrayList<String>();
child4.add("Goldy-35");
child4.add("Bubbles-36");
child4.add("dummy-37");
child4.add("Goldy-38");
child4.add("Bubbles-39");
child4.add("dummy-40");
child4.add("Goldy-41");
child4.add("Bubbles-42");
child4.add("dummy-43");
child4.add("Goldy-44");
child4.add("Bubbles-45");
child4.add("dummy-46");
child4.add("Goldy-47");
child4.add("Bubbles-48");
child4.add("dummy-49");
children.add(child4);
}
public Object getChild(int groupPosition, int childPosition) {
return children.get(groupPosition).get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
//if childern not avaibles.
return children.get(groupPosition).size();
}
private void getMoreData(int groupPosition, int childPosition){
Log.e("getMoreData", "calling groupPosition:"+groupPosition +"|childPosition:"+childPosition);
//remove the dummay record
children.get(groupPosition).remove(childPosition);
//adding a new group with data.
Random randomGenerator = new Random();
int count = randomGenerator.nextInt(100);
groups.add("More Data:" + count);
ArrayList<String> newData = new ArrayList<String>();
newData.add("Arnold"+count);
newData.add("Barry"+ count);
newData.add("Chuck"+ count);
newData.add("David"+ count);
children.add(newData);
//removing a record from exssitng group.
children.get(0).remove(0);
children.get(0).add("add to group0 shaggy");
//adding a record to group
children.get(1).add("shaggy add to group 2 shaggy");
//remove a groiup and corresponding childrens
groups.remove(2);
children.remove(2);
//adding a new record to last group.
children.get(groups.size()-1).add("new record");
//adding a dummy record to last group.
children.get(groups.size()-1).add("dummy");
}
public TextView getGenericView() {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 64);
TextView textView = new TextView(ExpandableList1.this);
textView.setLayoutParams(lp);
// Center the text vertically
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
textView.setPadding(36, 0, 0, 0);
return textView;
}
public Button getGenericButton(final int groupPosition,final int childPosition) {
// Layout parameters for the ExpandableListView
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, 64);
Button button = new Button(ExpandableList1.this);
button.setText("More");
button.setLayoutParams(lp);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
progressDialog = ProgressDialog.show(context, null, "Please Wait");
new Thread(){
/* (non-Javadoc)
* #see java.lang.Thread#run()
*/
#Override
public void run() {
getMoreData(groupPosition,childPosition);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
actionhandler.sendEmptyMessage(0);
}
}.start();
}
});
// Center the text vertically
button.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
button.setPadding(36, 0, 0, 0);
return button;
}
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
Log.e("getChildView", groupPosition + "===" +groups.size());
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.chilldlayout_data, null);
// parent.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
}
if( groupPosition == groups.size()-1 && isLastChild){
//adding a button.
Button button = (Button)convertView.findViewById(R.id.more_button);
button.setVisibility(View.VISIBLE);
button.setText("More");
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
progressDialog = ProgressDialog.show(context, null, "Please Wait");
new Thread(){
/* (non-Javadoc)
* #see java.lang.Thread#run()
*/
#Override
public void run() {
getMoreData(groupPosition,childPosition);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
actionhandler.sendEmptyMessage(0);
}
}.start();
}
});
// Center the text vertically
button.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
// Set the text starting position
button.setPadding(36, 0, 0, 0);
return convertView;
}else{
Button button = (Button)convertView.findViewById(R.id.more_button);
button.setVisibility(View.GONE);
TextView textView = (TextView)convertView.findViewById(R.id.textView_data);
textView.setText(getChild(groupPosition, childPosition).toString());
return convertView;
}
}
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
public int getGroupCount() {
return groups.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
TextView textView = getGenericView();
textView.setText(getGroup(groupPosition).toString());
return textView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
}

Categories

Resources