when scroll up & down in expandable list views get change - android

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

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

Android Volley Request does not work using the Expandable List View and Base Expandable List Adapter

Do not know why my volley request does not show any thing. It is not give me the failure instance but success listner does not call if I am using the ExpandableListView with BaseExpandableListAdapter.
See my Fragment class code: ShopCategoryFragment.java.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.examples.testone.domain.CategorySection;
import com.examples.testone.domain.ShopCategory;
import com.examples.testone.domain.ShopCategoryParent;
import com.examples.testone.domain.ShopCategorySection;
import com.examples.testone.domain.response.ShopCategorySectionsRestResponse;
import com.examples.testone.network.volley.GsonRequest;
public class ShopCategoryFragment extends Fragment {
// private ShopCategorySectionListAdapter shopCategorySectionListAdapter;
private RequestQueue requestQueue;
private boolean requestRunning = false;
private String volleyRequestMode = "in";
final String _appLogTag = " - ShopCategoryFragment - ";
private List<ShopCategorySectionVO> shopCategorySectionVOs;
Map<ShopCategorySectionVO, List<ShopCategory>> myMapCollection;
private ExpandableListView expListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setRetainInstance(true);
Log.d(_appLogTag, "Inside onCreate");
//this.requestQueue = SmartShopVolleySettings.getRequestQueue();
this.requestQueue = Volley.newRequestQueue(getActivity());
startRequest();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(_appLogTag, "Inside onCreateView");
View viewHierarchy =
inflater.inflate(R.layout.fragment_explist, container, false);
// List View Settings
expListView =
(ExpandableListView) viewHierarchy.findViewById(R.id.laptop_list);
// getActivity(), this.shopCategorySectionVOs, this.collection );
expListView.setAdapter
(new ShopCategoryExpandibleListAdapter(getActivity(),
shopCategorySectionVOs, myMapCollection));
return viewHierarchy;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d(_appLogTag, "Inside onViewCreated");
}
#Override
public void onDestroy() {
super.onResume();
Log.d(_appLogTag, "Inside onDestroy");
//this.requestQueue.cancelAll(this);
//this.requestRunning = false;
// cancelRequests();//Json shop lists
}
#Override
public void onPause() {
super.onPause();
Log.d(_appLogTag, "Inside onPause");
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// inflater.inflate(R.menu.simplemap_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
* switch (item.getItemId()) {
*
* case R.id.simplemap_menu_info:
* SimpleDialogFragment.createBuilder(this.getActivity(),
* this.getActivity().getSupportFragmentManager())
* .setMessage(Html.fromHtml
* (getString(R.string.simplemap_info_details)))
* .setTitle(R.string.simplemap_info_title) .show(); return true; }
*/
return super.onOptionsItemSelected(item);
}
private void startRequest() {
Log.d(_appLogTag,"Inside on Start Request for getting the Shop Categories ");
if ( !requestRunning ) {
ShopCategoryFragment.this.requestRunning = true ;
String url = getString(R.string.shops_category_get_url, this.volleyRequestMode);
Log.d(_appLogTag, "Url for json is:" + url);
GsonRequest<ShopCategorySectionsRestResponse> jsonObjectRequest =
new GsonRequest<ShopCategorySectionsRestResponse>(Method.GET,
url, ShopCategorySectionsRestResponse.class,
null,
getShopsCategoriesRequestSuccessListener(),
getShopsCategoriesRequestErrorListener());
jsonObjectRequest.setShouldCache(false);
//Log.i(_appLogTag, " volley request Finished: "+
jsonObjectRequest.getBodyContentType() + " More: " + jsonObjectRequest.toString());
this.requestQueue.add(jsonObjectRequest);
} else if (BuildConfig.DEBUG) {
Log.i(_appLogTag, " volley request is already running");
}
/*myMapCollection = new LinkedHashMap<ShopCategorySectionVO,
List<ShopCategory>>(); // My Map
shopCategorySectionVOs = new ArrayList<ShopCategorySectionVO>(); // My Section Headers
List<ShopCategory> shopCategories = new ArrayList<ShopCategory>();
ShopCategorySectionVO shopCategorySectionVO1 =
new ShopCategorySectionVO("Dog", "icon", null);
shopCategorySectionVOs.add(shopCategorySectionVO1);
ShopCategory sc1 = new ShopCategory();
Title sc1t1 = new Title();
sc1t1.setEn("Tommy");
sc1.setTitle(sc1t1);
Description sc1d1 = new Description();
sc1d1.setEn("My Kuta Tommy");
sc1.setDescr(sc1d1);
shopCategories.add(sc1);
ShopCategory sc2 = new ShopCategory();
Title sc1t2 = new Title();
sc1t2.setEn("Boomer");
sc2.setTitle(sc1t2);
Description sc1d2 = new Description();
sc1d2.setEn("My Kuta Boomer");
sc2.setDescr(sc1d2);
shopCategories.add(sc2);
myMapCollection.put(shopCategorySectionVO1, shopCategories);*/
}
private Response.Listener<ShopCategorySectionsRestResponse>
getShopsCategoriesRequestSuccessListener() {
return new Response.Listener<ShopCategorySectionsRestResponse>() {
#Override
public void onResponse(ShopCategorySectionsRestResponse response) {
myMapCollection = new LinkedHashMap<ShopCategorySectionVO, List<ShopCategory>>();
shopCategorySectionVOs = new ArrayList<ShopCategorySectionVO>();
List<ShopCategory> shopCategories = new ArrayList<ShopCategory>();
Log.d(_appLogTag,"Ready for going inside");
for (CategorySection categorySection :response.getShop_category_sections()) {
Log.d(_appLogTag,"Inside Outer For");
ShopCategorySection catSection = categorySection.getShopCategorySection();
ShopCategorySectionVO shopCategorySectionVO =
new ShopCategorySectionVO
(catSection.getTitle(),catSection.getIcon(),
catSection.getBackcolor());
shopCategorySectionVOs.add(shopCategorySectionVO);
if (catSection.getShop_categories() != null &&
catSection.getShop_categories().size() > 0) {
Log.d(_appLogTag,"Inside Inner If");
for (ShopCategoryParent shopCategoryParent : catSection.getShop_categories()) {
Log.d(_appLogTag,"Inside Inner For");
ShopCategory shopCategory = shopCategoryParent.getShopCategory();
shopCategories.add(shopCategory);
}// End of child For
}// End of IF
myMapCollection.put(shopCategorySectionVO, shopCategories); // Filling of Map
}
// End of Outer For
requestRunning = false;
}
};
}
private Response.ErrorListener getShopsCategoriesRequestErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(_appLogTag,"Inside on create Shops Request Error Listener ");
requestRunning = false;
}
};
}
}
and my BaseExpandableListAdapter.
public class ShopCategoryExpandibleListAdapter extends BaseExpandableListAdapter {
final String _appLogTag = " - ShopCategoryExpandibleListAdapter - ";
// Define activity context
private Context mContext;
/*
* Here we have a Hashmap containing a String key
* (can be Integer or other type but I was testing
* with contacts so I used contact name as the key)
*/
private Map<ShopCategorySectionVO, List<ShopCategory>> mListDataChild;
// ArrayList that is what each key in the above
// hashmap points to
private List<ShopCategorySectionVO> mCategorySectionVOs;
// Hashmap for keeping track of our checkbox check states
private Map<Integer, boolean[]> mChildCheckStates;
// Our getChildView & getGroupView use the viewholder patter
// Here are the viewholders defined, the inner classes are
// at the bottom
private ChildViewHolder childViewHolder;
private GroupViewHolder groupViewHolder;
/*
* For the purpose of this document, I'm only using a single
* textview in the group (parent) and child, but you're limited only
* by your XML view for each group item :)
*/
private String groupText;
private String childText;
//private String childText2;
/* Here's the constructor we'll use to pass in our calling
* activity's context, group items, and child items
*/
public ShopCategoryExpandibleListAdapter(Context context,
List<ShopCategorySectionVO> listDataGroup,
Map<ShopCategorySectionVO, List<ShopCategory>> listDataChild) {
Log.d(_appLogTag, "Inside Constructor");
mContext = context;
mCategorySectionVOs = listDataGroup;
mListDataChild = listDataChild;
// Initialize our hashmap containing our check states here
mChildCheckStates = new HashMap<Integer, boolean[]>();
}
#Override
public ShopCategory getChild(int groupPosition, int childPosition) {
Log.d(_appLogTag, "Inside getChild");
List<ShopCategory>
listOfChilds = mListDataChild.get(mCategorySectionVOs.get(groupPosition));
Log.d(_appLogTag, "So total number of childs in Group number "
+groupPosition+" are "+listOfChilds.size());
//return mListDataChild.get(mCategorySectionVOs.get(groupPosition)).get(childPosition);
return listOfChilds.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
Log.d(_appLogTag, "Inside getChild ID");
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
Log.d(_appLogTag, "Inside getChild View");
final int mGroupPosition = groupPosition;
final int mChildPosition = childPosition;
// I passed a text string into an activity holding a getter/setter
// which I passed in through "ExpListChildItems".
// Here is where I call the getter to get that text
//childText = getChild(mGroupPosition, mChildPosition).getChildText();
ShopCategory shopCategory = getChild(mGroupPosition, mChildPosition);
childText = shopCategory.getTitle().getEn();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_item, null);
childViewHolder = new ChildViewHolder();
childViewHolder.mChildText = (TextView) convertView.findViewById(R.id.laptop_child);
childViewHolder.mCheckBox = (CheckBox) convertView
.findViewById(R.id.checkBox);
convertView.setTag(R.layout.child_item, childViewHolder);
} else {
childViewHolder = (ChildViewHolder) convertView
.getTag(R.layout.child_item);
}
childViewHolder.mChildText.setText(childText);
//childViewHolder.mChildText2.setText(childText2);
/*
* You have to set the onCheckChangedListener to null
* before restoring check states because each call to
* "setChecked" is accompanied by a call to the
* onCheckChangedListener
*/
childViewHolder.mCheckBox.setOnCheckedChangeListener(null);
if (mChildCheckStates.containsKey(mGroupPosition)) {
/*
* if the hashmap mChildCheckStates<Integer, Boolean[]> contains
* the value of the parent view (group) of this child (aka, the key),
* then retrive the boolean array getChecked[]
*/
boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
// set the check state of this position's checkbox based on the
// boolean value of getChecked[position]
childViewHolder.mCheckBox.setChecked(getChecked[mChildPosition]);
} else {
/*
* if the hashmap mChildCheckStates<Integer, Boolean[]> does not
* contain the value of the parent view (group) of this child (aka, the key),
* (aka, the key), then initialize getChecked[] as a new boolean array
* and set it's size to the total number of children associated with
* the parent group
*/
boolean getChecked[] = new boolean[getChildrenCount(mGroupPosition)];
// add getChecked[] to the mChildCheckStates hashmap using mGroupPosition as the key
mChildCheckStates.put(mGroupPosition, getChecked);
// set the check state of this position's checkbox based on the
// boolean value of getChecked[position]
childViewHolder.mCheckBox.setChecked(false);
}
childViewHolder.mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
getChecked[mChildPosition] = isChecked;
mChildCheckStates.put(mGroupPosition, getChecked);
} else {
boolean getChecked[] = mChildCheckStates.get(mGroupPosition);
getChecked[mChildPosition] = isChecked;
mChildCheckStates.put(mGroupPosition, getChecked);
}
}
});
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
Log.d(_appLogTag, "Inside getChildrenCount");
//ShopCategory childList = mListDataChild.get(mCategorySectionVOs.get(groupPosition));
return mListDataChild.get(mCategorySectionVOs.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
Log.d(_appLogTag, "Inside getGroup");
return mCategorySectionVOs.get(groupPosition);
}
#Override
public int getGroupCount() {
Log.d(_appLogTag, "Inside getGroupCount");
return mCategorySectionVOs.size();
}
#Override
public long getGroupId(int groupPosition) {
Log.d(_appLogTag, "Inside getGroupId");
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// I passed a text string into an activity holding a getter/setter
// which I passed in through "ExpListGroupItems".
// Here is where I call the getter to get that text
//groupText = getGroup(groupPosition).getGroupText();
Log.d(_appLogTag, "Inside getGroupView");
groupText = ((ShopCategorySectionVO)getGroup(groupPosition)).getTitle();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.group_item, null);
// Initialize the GroupViewHolder defined at the bottom of this document
groupViewHolder = new GroupViewHolder();
//groupViewHolder.mGroupText = (TextView) convertView.findViewById(R.id.groupTextView);
groupViewHolder.mGroupText = (TextView) convertView.findViewById(R.id.laptop_head);
convertView.setTag(groupViewHolder);
} else {
groupViewHolder = (GroupViewHolder) convertView.getTag();
}
groupViewHolder.mGroupText.setText(groupText);
return convertView;
}
#Override
public boolean hasStableIds() {
Log.d(_appLogTag, "Inside hasStableIds");
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
Log.d(_appLogTag, "Inside isChildSelectable");
return false;
}
public final class GroupViewHolder {
TextView mGroupText;
}
public final class ChildViewHolder {
TextView mChildText;
TextView mChildText2;
CheckBox mCheckBox;
}
}
It does not make any sense If I just disable the adapter, volley request got get success and load data in my domain classes.
I think the mistake is that you want to fill ExpandableListView with data that are not loaded yet. In your onCreateView the myMapCollection is still empty. It is loaded after some time when the volley finishes its asyncTask. You need to refresh your UI when you get successful response that volley finished loading data.

EditText disappears after closing expandedView

The problem I am having is the text that I type in the expanded view, is not being saved. The moment I close one group to open another, all the values saved in the first disappear. Can anyone advise me what to do so it can be saved not just for when I open the expandedView but also for when I restart it or resume it. I'm not sure how to use the onResume and onRestart functions. Thanks
I am attaching the code as well:
import android.content.Context;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseExpandableListAdapter
{
private int counter;
SharedPreferences getPrefs;
private Context context;
String[] parent= new String [4];
String[][] child= new String [4][4];
String [][] weights= new String [4][4];
boolean KU=false;
boolean MC=false;
boolean TI=false;
boolean C=false;
boolean allEdited=false;
EditText et1;
EditText et2;
EditText et3;
EditText et4;
public MyAdapter(Context context)
{
this.context=context;
}
#Override
public Object getChild(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
ViewGroup parent)
{
counter++;
if (!allEdited)
{
et1= new EditText (context);
et2= new EditText (context);
et3= new EditText (context);
et4= new EditText (context);
child[groupPosition][0]=et1.getText().toString();
child[groupPosition][1]=et2.getText().toString();
child[groupPosition][2]=et3.getText().toString();
child[groupPosition][3]=et4.getText().toString();
}
if(!KU)
{
et1.setText(child[groupPosition][childPosition]);
et1.setPadding(50, 10, 10, 10);
et1.setTextSize(15);
et1.setTextColor(Color.WHITE);
et1.setFocusable(true);
et1.setInputType(0x00000002);
weights[groupPosition][0]=(et1.getText().toString());
}
if (!et1.getText().toString().equals(""))
{
KU=true;
}
if(KU)
{
et1.setText(weights[groupPosition][0]);
et1.setFreezesText(true);
}
if (!MC)
{
et2.setText(child[groupPosition][childPosition]);
et2.setPadding(50, 10, 10, 10);
et2.setTextSize(15);
et2.setTextColor(Color.WHITE);
et2.setFocusable(true);
et2.setInputType(0x00000002);
weights[groupPosition][1]=(et2.getText().toString());
}
else if (!et2.getText().toString().equals(""))
{
MC=true;
}
weights[groupPosition][1]=(et2.getText().toString());
if(MC)
{
et1.setText(weights[groupPosition][1]);
}
if (!TI)
{
et3.setText(child[groupPosition][childPosition]);
et3.setPadding(50, 10, 10, 10);
et3.setTextSize(15);
et3.setTextColor(Color.WHITE);
et3.setFocusable(true);
et3.setInputType(0x00000002);
weights[groupPosition][2]=(et3.getText().toString());
}
else if (!et3.getText().toString().equals(""))
{
TI=true;
}
weights[groupPosition][2]=(et3.getText().toString());
if(TI)
{
et3.setText(weights[groupPosition][2]);
}
if (!C)
{
et4.setText(child[groupPosition][childPosition]);
et4.setPadding(50, 10, 10, 10);
et4.setTextSize(15);
et4.setTextColor(Color.WHITE);
et4.setFocusable(true);
et4.setInputType(0x00000002);
weights[groupPosition][3]=(et4.getText().toString());
}
else if (!et4.getText().toString().equals(""))
{
C=true;
}
weights[groupPosition][3]=(et1.getText().toString());
if(C)
{
et4.setText(weights[groupPosition][3]);
}
if (KU && MC && TI && C)
{
allEdited=true;
}
if (counter==1)
return et1;
else if (counter==2)
return et2;
else if (counter==3)
return et3;
else if (counter==4)
return et4;
else
counter=0; return et1;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return child[groupPosition].length;
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public int getGroupCount()
{
return parent.length;
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
TextView tv= new TextView (context);
this.parent[groupPosition]=tv.getText().toString();
getPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String allCourses= getPrefs.getString("allClasses", "Please enter your course code");
String[] courses= allCourses.split(",");
for (int i=0;i<courses.length;i++)
{
this.parent[i]=courses[i];
}
tv.setText(this.parent[groupPosition]);
tv.setPadding(50, 10, 10, 10);
tv.setTextSize(20);
tv.setTextColor(Color.GREEN);
return tv;
}
you should use a Custom List Adapter, and whenever you type something in textview, have a list and assign it to the list for particular index(position)
As #Kapil said you can use list to store the values but those values will be destroyed once the activity is destroyed. If you want a permanent storage i.e. the values should remain even if you restart the app the should use Shared Preferences or SQLite Database.

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!

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