Custom Adapter with Expandable Listview - java

Can any one help me with this...I'm trying to implement expandable listview dynamically and i used one of the tutorials (Androidhive) to get familiar to it. My problem is that i am getting my data from parse.com and i want to load it dynamically into the expandable listview. First i am getting data from parse into my object classified by each type and then i suppose to convert that to the expandable listview. What i am stuck in is that i don't know how to pass to the adapter more than 1 object to the child (i have 3 textviews on each child). From the below example i got the data of main road from only to be viewed in the child but i still need to get 2 additional values which i don't know how to achieve.
Hereunder my code for the asynctask :
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
// mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("wait please ...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
listviewPostsGet = new ArrayList<listviewPostsGet>();
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"MainRoadsList");
try {
ob = query.find();
for (ParseObject country : ob) {
listviewPostsGet map = new listviewPostsGet();
map.setmainroad(((String) country.get("mainroad")));
map.setmainroadfrom(((String) country.get("from")));
map.setmainroadto((String) country.get("to"));
map.setcategory(((String) country.get("mainroad")));
listviewPostsGet.add(map);
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
String check = "";
for (int i = 0; i < listviewPostsGet.size(); i++)
{
String XX = listviewPostsGet.get(i).getcategory()
.toString();
if (!check.contentEquals(XX.toString())) {
listDataHeader.add(XX);
check = XX;
List<String> TTT = new ArrayList<String>();
for (int j = 0; j < listviewPostsGet.size(); j++) {
String YY = listviewPostsGet.get(j).getcategory().toString();
if (YY.contentEquals(XX.toString()))
{
TTT.add(listviewPostsGet.get(j).getmainroadfrom().toString()+" "+listviewPostsGet.get(j).getmainroadto().toString());
listDataChild.put(XX, TTT);
}
}
}
}
}
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
listAdapter = new ExpandableListAdapter1(MainActivity.this,
listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
mProgressDialog.dismiss();
}
}
Also here is the adapter :
public class ExpandableListAdapter1 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 ExpandableListAdapter1(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listDataChild ) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listDataChild;
}
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition).toString())
.get(childPosititon);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
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.mainlayout, null);
}
TextView from = (TextView) convertView
.findViewById(R.id.fromroad);
TextView to = (TextView) convertView
.findViewById(R.id.toroad);
from.setText(childText);
return convertView;
}
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
public int getGroupCount() {
return this._listDataHeader.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
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;
}
public boolean hasStableIds() {
return false;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Edit :
to be clear , My problem is that I want to assign 3 values from my listviewPostsGet to the expandable listview child and what i can actually achieve is to pass only 1 value which is "Main road from" to the TTT array list then assign it to the corresponding textview on the adapter.

Related

hashmap to show data in expandable listview in android

I am trying to show data in an expandable listview from server in android. I am trying to implement hashmap within the AsyncTask. Please see the following code.
private class HttpAsyncTaskReports extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
public HttpAsyncTaskReports(ExpandableActivity activity) {
dialog = new ProgressDialog(activity);
}
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
#Override
protected void onPreExecute() {
// Removes all markers, overlays, and polylines from the map.
dialog.setMessage("Loading reports, please wait.");
dialog.show();
}
#Override
protected void onPostExecute(String result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Header, Child data
List<String> top250 = new ArrayList<String>();
top250.add("The Shawshank Redemption");
top250.add("The Godfather");
try {
JSONArray jArray = new JSONArray(result);
JSONObject jsonobject = jArray.getJSONObject(0);
JSONArray jsonAssets = jsonobject.getJSONArray("last_data");
Log.d("LASTLATLONG", result);
for (i = 0; i < jsonAssets.length(); i++) {
JSONObject nlmJsonObject = jsonAssets.getJSONObject(i);
JSONObject lastData_JsonObject = nlmJsonObject.getJSONObject("last_data");
JSONObject lastData_timeJsonObject = lastData_JsonObject.getJSONObject("time");
// JSONObject lastData_dateJsonObject = lastData_timeJsonObject.getJSONObject("$date");
// JSONObject lastData_speedJsonObject = lastData_JsonObject.getJSONObject("speed");
// Adding child data
listDataHeader.add(lastData_timeJsonObject.getString("$date"));
listDataChild.put(listDataHeader.get(i), top250);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Server Error :( Please wait!", Toast.LENGTH_LONG).show();
}
}
}
Here is the ExpandableListAdapter class
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;
}
}
Here is the error....
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3124)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3233)
at android.app.ActivityThread.access$1000(ActivityThread.java:197)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6856)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at gps.finder.com.findermaterial.ExpandableListAdapter.getGroupCount(ExpandableListAdapter.java:75)
at android.widget.ExpandableListConnector.getCount(ExpandableListConnector.java:397)
at android.widget.ListView.setAdapter(ListView.java:502)
at android.widget.ExpandableListView.setAdapter(ExpandableListView.java:604)
at gps.finder.com.findermaterial.ExpandableActivity.onCreate(ExpandableActivity.java:102)
at android.app.Activity.performCreate(Activity.java:6550)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1120)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3077)
Can anybody tell me how should I solve this issue?
If I use a function like the following one to list data, it works successfully.
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Top 50");
listDataHeader.add("Now Showing");
listDataHeader.add("Coming Soon..");
// Adding child data
List<String> top250 = new ArrayList<String>();
top250.add("The Shawshank Redemption");
top250.add("The Godfather");
top250.add("The Godfather: Part II");
top250.add("Pulp Fiction");
top250.add("The Good, the Bad and the Ugly");
top250.add("The Dark Knight");
top250.add("12 Angry Men");
List<String> nowShowing = new ArrayList<String>();
nowShowing.add("The Conjuring");
nowShowing.add("Despicable Me 2");
nowShowing.add("Turbo");
nowShowing.add("Grown Ups 2");
nowShowing.add("Red 2");
nowShowing.add("The Wolverine");
List<String> comingSoon = new ArrayList<String>();
comingSoon.add("2 Guns");
comingSoon.add("The Smurfs 2");
comingSoon.add("The Spectacular Now");
comingSoon.add("The Canyons");
comingSoon.add("Europa Report");
listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
listDataChild.put(listDataHeader.get(1), nowShowing);
listDataChild.put(listDataHeader.get(2), comingSoon);
}
But I need to implement the hashmap using the data retrieve from server.
I appreciate your suggestions. Thanks in advance.

How to add different image for each group in expandable Listview

In my Expandable Listview, have three groups. I want to add different three image for that group. i tried many codes, but not working.
My code:
Main Activity:
HashMap<String, List<String>> rightDrawerListDetail = getData();
List<String> rightDrawerListTitle = new ArrayList<String>(rightDrawerListDetail.keySet());
adapterR = new CustomExpandableListAdapter(this, rightDrawerListTitle,rightDrawerListDetail);
mRightDrawerList.setAdapter(adapterR);
private HashMap<String, List<String>> getData(){
HashMap<String, List<String>> expandableListDetail = new HashMap<String, List<String>>();
ArrayList<String> arrayList = mydb.getAllAddress();
List asRider = new ArrayList();
asRider.add("hello");
List asRidee = new ArrayList();
asRidee.add("hai");
List recent = new ArrayList();
recent.add("Success");
expandableListDetail.put("As a Rider",asRider);
expandableListDetail.put("As a Ridee",asRidee);
expandableListDetail.put("My Recent Activities",recent);
return expandableListDetail;
}
CustomExpandableListAdapter.java:
public class CustomExpandableListAdapter extends BaseExpandableListAdapter {
private Context mContext;
private List<String> mGroups;
private LayoutInflater mInflater;
private HashMap<String, List<String>> mexpandableListDetail;
public CustomExpandableListAdapter(Context context, List<String> groups,HashMap<String, List<String>> expandableListDetail) {
mContext = context;
mGroups = groups;
mexpandableListDetail = expandableListDetail;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getGroupCount() {
return mGroups.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return mexpandableListDetail.get(mGroups.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return mGroups.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return mexpandableListDetail.get(mGroups.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.right_drawer_group, null);
}
// Get the group item
String listTitle = (String) getGroup(groupPosition);
// Set group name
TextView textView = (TextView) convertView.findViewById(R.id.textGroup);
textView.setText(listTitle);
ImageView indicator = (ImageView) convertView.findViewById(R.id.groupIndicator);
if (isExpanded) {
indicator.setImageResource(R.drawable.arrowup);
} else {
indicator.setImageResource(R.drawable.arrowdown);
}
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.right_drawer_child, null);
}
// Get child name
String children = (String) getChild(groupPosition, childPosition);
// Set child name
TextView text = (TextView) convertView.findViewById(R.id.textChild);
text.setText(children);
/*convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, children, Toast.LENGTH_SHORT).show();
}
});*/
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Please anyone help to me!
Thanks in advance
In your right_drawer_group.xml add an ImageView where you want your group image to be placed, lets say groupImage.
In your getGroupView:
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.right_drawer_group, null);
}
//Set group image
ImageView groupImage = (ImageView)convertView.findViewById(R.id.groupImage);
switch((String)getGroup(groupPosition))
{
case "As a Rider":
//groupImage set correct image
break;
case "As a Ridee":
//groupImage set correct image
break;
case "My Recent Activities":
//groupImage set correct image
break;
}
// Get the group item
String listTitle = (String) getGroup(groupPosition);
// Set group name
TextView textView = (TextView) convertView.findViewById(R.id.textGroup);
textView.setText(listTitle);
ImageView indicator = (ImageView) convertView.findViewById(R.id.groupIndicator);
if (isExpanded) {
indicator.setImageResource(R.drawable.arrowup);
} else {
indicator.setImageResource(R.drawable.arrowdown);
}
return convertView;
}
It's not the most neat solution as if you change the group name this will break, but it will work for now. Better solution would be is to pass the groups as objects containing getName and getImageId.

How to use set changes in list when one row deleted

I'm using expandable listView and Expandable ListAdapter.
ChlidView show me the titles and child View show me the subTitle .
In the "child View" i have a button that delete the the specific row .
i have two classes, one for loading the data from database into the hashMap and the second class for the ExpandableListAdapter. i create the onClick method on the adapter class , and the delete function is working, but the list not refreshing the updated data. i know i need to load again the data to the hashMap but the adapter class is outSide the first class. i'm trying to use "notifyDataSetChanged" and no result too.
class 1 :
hand = new DbHandler(getActivity());
fullList = new HashMap<ArrayList<ClockModel>, ArrayList<ClockModel>>();
temp = new ArrayList<ClockModel>();
ArrayList<ClockModel> child = new ArrayList<ClockModel>();
child = hand.getDay(workName);
for (int i = 0; i < child.size(); i++) {
if(child.get(i).getDateMonth() == month && child.get(i).getDateYear()==year){
ClockModel m1 = new ClockModel(
child.get(i).getId(),
child.get(i).getWorkName(),
child.get(i).getDateDay(),
child.get(i).getDateMonth(),
);
temp.add(m1);
fullList.put(temp, temp);
}
}
adapter = new ExpandableListCustom(getActivity(), fullList,temp);
lv.setAdapter(adapter);
adapter :
#Override
public View getChildView(final 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.row_child,null);
}
TextView txMyVal = (TextView) convertView.findViewById(R.id.row_myVal);
TextView txBreakTime = (TextView) convertView.findViewById(R.id.row_breakTime);
TextView txComment = (TextView) convertView.findViewById(R.id.row_comments);
TextView txNameOfDay = (TextView) convertView.findViewById(R.id.row_nameOfDay);
String comments= fullList.get(child).get(groupPosition).getComment();
nameOfDay= fullList.get(child).get(groupPosition).getNameOfDay();
shiftType= fullList.get(child).get(groupPosition).getShiftType();
int breakTime= fullList.get(child).get(groupPosition).getBreakTime();
currentPosition = fullList.get(child).get(groupPosition).getId();
btnRemove = (ImageButton) convertView.findViewById(R.id.row_btnRemove);
btnRemove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
hand.deleteDay(currentPosition);
Toast.makeText(context, "Del : "+currentPosition, 2000).show();
}
});
public class ExpandableListCustom extends BaseExpandableListAdapter implements OnClickListener {
DbHandler hand;
private Context context;
private HashMap<ArrayList<ClockModel>,ArrayList<ClockModel> > fullList; //Headers
ArrayList<ClockModel> child; //data
MySharedPreferences preferences;
public ExpandableListCustom(Context context,
HashMap<ArrayList<ClockModel>, ArrayList<ClockModel>> fullList,
ArrayList<ClockModel> child) {
super();
this.context = context;
this.fullList = fullList;
this.child = child;
clockSet = new Clock();
preferences = new MySharedPreferences(context);
hand = new DbHandler(context);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return this.fullList.get(this.fullList.get(childPosition));
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(final 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.row_child,null);
}
TextView txMyVal = (TextView) convertView.findViewById(R.id.row_myVal);
TextView txBreakTime = (TextView) convertView.findViewById(R.id.row_breakTime);
TextView txComment = (TextView) convertView.findViewById(R.id.row_comments);
TextView txNameOfDay = (TextView) convertView.findViewById(R.id.row_nameOfDay);
enterHour= (int) fullList.get(child).get(groupPosition).getEnterHour();
exitHour= (int) fullList.get(child).get(groupPosition).getExitHour();
enterMin= (int) fullList.get(child).get(groupPosition).getEnterMin();
exitMin= (int) fullList.get(child).get(groupPosition).getExitMin();
currentPosition = fullList.get(child).get(groupPosition).getId();
btnRemove = (ImageButton) convertView.findViewById(R.id.row_btnRemove);
btnRemove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
hand.deleteDay(currentPosition);
Toast.makeText(context, "Del : "+currentPosition, 2000).show();
}
});
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub //////////////////////////////////////////
// return this.fullList.get(groupPosition).size();
if(fullList != null){
return 1;
}else{
return 0;
}
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return this.fullList.get(child).get(groupPosition);
}
#Override
public int getGroupCount() {
if(fullList != null){
return this.fullList.size();
}else{
return 0;
}
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
int dateDay= fullList.get(child).get(groupPosition).getDateDay();
int dateMonth= fullList.get(child).get(groupPosition).getDateMonth();
int dateYear= fullList.get(child).get(groupPosition).getDateYear();
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.row_header, null);
}
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
}
Now when you delete the item from the database you need at the same time to remove it from the adapter and call notifyDataSetChanged():
#Override
public void onClick(View v) {
hand.deleteDay(currentPosition);
fullList.remove(currentPosition);
notifyDataSetChanged();
}
you need to fetch data from database and assign to arraylist "fullList" which is used for adapter when you delete the data and use ...
notifyDataSetChanged();
method of adapter...

How to convert a set to list ? The set is used as a key in Hashmap

Hi I an using an expandable listview in android. For populating the list I am using an hashmap as i want to map the corresponding categories to its child. My hashmap is like Hashmap> .Now the following code is used :
public class ExpandableListAdapter extends BaseExpandableListAdapter
{
private Context _context;
// child data in format of header title, child title
private Map<SaleDetailsMenuItems, List<ModifList>> _listDataChild;
public ExpandableListAdapter(Context context, Map<SaleDetailsMenuItems, List<ModifList>> listChildData)
{
this._context = context;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon)
{
Set<SaleDetailsMenuItems> s = _listDataChild.keySet();
SaleDetailsMenuItems key = (SaleDetailsMenuItems) s.toArray()[groupPosition];
//List<SaleDetailsMenuItems> list = new ArrayList<SaleDetailsMenuItems>(s);
//Log.e("Child in adapter get Child","get child "+this._listDataChild.get(key).get(childPosititon));
return this._listDataChild.get(key).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)
{
String childText = ((ModifList)getChild(groupPosition, childPosition)).getName();
String childText1 = "1";
String childText2 = ((ModifList)getChild(groupPosition, childPosition)).getPrice();
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);
TextView txtListChild1 = (TextView) convertView.findViewById(R.id.lblListItem1);
TextView txtListChild2 = (TextView) convertView.findViewById(R.id.lblListItem2);
txtListChild.setText(childText);
txtListChild1.setText(childText1);
txtListChild2.setText(childText2);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition)
{
SaleDetailsMenuItems key ;
try
{
Set<SaleDetailsMenuItems> s = _listDataChild.keySet();
key = (SaleDetailsMenuItems) s.toArray()[groupPosition];
// List<SaleDetailsMenuItems> list = new ArrayList<SaleDetailsMenuItems>(s);
//Log.e("Child size in adapter ","get children count "+this._listDataChild.get(key).size());
this._listDataChild.get(key).size();
}
catch(NullPointerException e)
{
e.printStackTrace();
return 0;
}
return this._listDataChild.get(key).size();
}
#Override
public Object getGroup(int groupPosition)
{
Set<SaleDetailsMenuItems> s = _listDataChild.keySet();
//List<SaleDetailsMenuItems> list = new ArrayList<SaleDetailsMenuItems>(s);
SaleDetailsMenuItems key = (SaleDetailsMenuItems) s.toArray()[groupPosition];
//Log.e("adapter get group ","get group "+key);
return key;
}
#Override
public int getGroupCount()
{
//Log.e("Group Count","Group Count "+_listDataChild.keySet().size());
return _listDataChild.keySet().size();
}
#Override
public long getGroupId(int groupPosition)
{
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent)
{
final int index = groupPosition;
ExpandableListView mExpandableListView = (ExpandableListView) parent;
mExpandableListView.expandGroup(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);
TextView lblListHeader1 = (TextView) convertView.findViewById(R.id.lblListquantity1);
TextView lblListHeader2 = (TextView) convertView.findViewById(R.id.lblListprice1);
Button add = (Button) convertView.findViewById(R.id.btnadd);
Button minus = (Button) convertView.findViewById(R.id.Button01);
lblListHeader.setText(((SaleDetailsMenuItems) getGroup(groupPosition)).getName().toString());
lblListHeader1.setText(((SaleDetailsMenuItems) getGroup(groupPosition)).getQuantity().toString());
lblListHeader2.setText(((SaleDetailsMenuItems) getGroup(groupPosition)).getPrice().toString());
minus.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
listviewAdapter.notifyDataSetChanged();
putminusquantity(index);
//listviewAdapter.notifyDataSetChanged();
}
});
add.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
//Toast.makeText(context, shankar, Toast.LENGTH_SHORT).show();
//DeleteOrderScreen del = new DeleteOrderScreen();
listviewAdapter.notifyDataSetChanged();
putaddquantity(index);
//listviewAdapter.notifyDataSetChanged();
}
});
return convertView;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return true;
}
}
In this,set is used to get the keyset from Hashmap.as set is unordered i got the list in unordered form .I want the expandable list in ordered form. So how to make my list ordered?? Please reply me as soon as possible.
One possibility is that you dont use HashMap or HashSet but TreeMap and TreeSet.
eithe rthe objects you enter already have a correct compareTo methods, or You have to use a custom comparator which you provide in the constructor of TreeMap or TreeSet.
Then the map or set are sorted: Example:
// auto sorted because Integer implements Comparable
SortedSet set = new TreeSet<Integer>();
// asume MyObject implements Comparable
SortedSet set = new TreeSet<MyObject>();
// asume MyObject needs a special other sorting
SortedSet set = new TreeSet<MyObject>(MyCustomComparator);
similar for Maps:
Map map = new TreeMap<Integer>;
or you also can use
SortedMap map = new TreeMap<Integer>;

I have call another Activity when i click on child view of expandable listview in Android?

I want to call another activity when i click button which is child view of expandable listview in Android.When i run the activity does not show the expandable listview.How to work on exapandable list view.Can some one give me idea how to do this.
Here is my Activity code
public class My_Project extends ExpandableListActivity
{
ExpandableListView expListView;
Button btnNewProject;
Button btn_myprojectdefinemyteam;
DBHelper databaseHelper;
SQLiteDatabase db;
ImageView imgButtonBack;
List dispDataList;
String[] array;
String[] Task_Title_Size;
String[] Task_Start_Date_Size;
String[] Task_CompletionDate_Size;
String[] Task_CompletionTime_Size;
String[] Task_Description_Size;
String[] Task_Status_Size;
String[] Task_IsActive_Size;
String[] dtrProjectNAmeSize;
public static final String Task_Title = "Task_Titles";
public static final String Task_Start_Date = "start_date";
public static final String Task_CompletionDate = "completion_date";
public static final String Task_CompletionTime = "completion_time";
public static final String Task_Description = "task_description";
public static final String Task_Status = "task_status";
public static final String Task_IsActive ="IS_Active";
private int ParentClickStatus=-1;
private int ChildClickStatus=-1;
Myexpandable_ListAdapter mAdapter;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.my_project);
imgButtonBack = (ImageView)findViewById(R.id.imagBackButton);//ImageView imgButtonBack;
imgButtonBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent iBack = new Intent(My_Project.this , Menu.class);
startActivity(iBack);
finish();
}
});
expListView = (ExpandableListView) findViewById(android.R.id.list);
databaseHelper = new DBHelper(getApplicationContext());
dispDataList=databaseHelper.viewMyProjectDetals();
dtrProjectNAmeSize=new String[dispDataList.size()];
System.out.println(" dtrProjectNAmeSize = " + dtrProjectNAmeSize);
if ( dispDataList.size() > 6 )
{
Task_Title_Size=(String[])dispDataList.get(0);
Task_Start_Date_Size=(String[]) dispDataList.get(1);
Task_CompletionDate_Size = (String[])dispDataList.get(2);
Task_CompletionTime_Size=(String[])dispDataList.get(3);
Task_Description_Size=(String[]) dispDataList.get(4);
Task_Status_Size = (String[])dispDataList.get(5);
Task_IsActive_Size = (String[])dispDataList.get(6);
for(int i=0;i<Task_Title_Size.length;i++)
{
System.out.println("New data :"+Task_Title_Size[i]);
}
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
for (int i = 0; i < Task_Title_Size.length ; i++)
{
Map<String, String> curGroupMap = new HashMap<String, String>();
groupData.add(curGroupMap);
curGroupMap.put(Task_Title,"" +Task_Title_Size[i]);
List<Map<String, String>> children = new ArrayList<Map<String, String>>();
Map<String, String> curChildMap = new HashMap<String, String>();
children.add(curChildMap);
curChildMap.put(Task_Start_Date,"" +Task_Start_Date_Size[i]);
curChildMap.put(Task_CompletionDate,"" +Task_CompletionDate_Size[i]);
curChildMap.put(Task_CompletionTime,"" +Task_CompletionTime_Size[i]);
curChildMap.put(Task_Description,"" +Task_Description_Size[i]);
curChildMap.put(Task_Status,"" +Task_Status_Size[i]);
curChildMap.put(Task_IsActive,"" +Task_IsActive_Size[i]);
childData.add(children);
}
mAdapter =new Myexpandable_ListAdapter(
this,
groupData,
R.layout.list_group,
new String[] { Task_Title },
new int[] {R.id.lblListHeader },
childData,
R.layout.child_item,
new String[] { Task_Start_Date , Task_CompletionDate , Task_CompletionTime , Task_Description , Task_Status , Task_IsActive},
new int[] { R.id.TextView_Projectdetails , R.id.textOne , R.id.textTwo , R.id.textThree , R.id.textFour, R.id.textFive}
);
expListView.setAdapter(mAdapter);
}
expListView.setOnGroupClickListener(new OnGroupClickListener()
{
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id)
{
return false;
}
});
//editTextTaskName = (EditText)findViewById(R.id.Task_Name);
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
dtrProjectNAmeSize.length + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
dtrProjectNAmeSize.length + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
btnNewProject = (Button)findViewById(R.id.buttonmyproject_NewProject);
btnNewProject.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(My_Project.this , Add_Project.class);
startActivity(i);
finish();
}
});
}
private class Myexpandable_ListAdapter extends BaseExpandableListAdapter {
public Myexpandable_ListAdapter(Context context,
List<? extends Map<String, ?>> groupData,
int expandedGroupLayout,
String[] groupFrom, int[] groupTo,
List<? extends List<? extends Map<String, ?>>> childData,
int childLayout, String[] childFrom,
int[] childTo) {
super();
// TODO Auto-generated constructor stub
}
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
Context context;
public Object getChild(int groupPosition, int childPosition)
{
//this.get(groupPosition).getChildren().get(childPosition);
String strchildPosition = this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosition);
System.out.println("Child Position =" + strchildPosition);
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosition);
}
//Call when child row clicked
#Override
public long getChildId(int groupPosition, int childPosition)
{
/****** When Child row clicked then this function call *******/
//Log.i("Noise", "parent == "+groupPosition+"= child : =="+childPosition);
if( ChildClickStatus!=childPosition)
{
ChildClickStatus = childPosition;
Toast.makeText(getApplicationContext(), "Parent :"+groupPosition + " Child :"+childPosition ,
Toast.LENGTH_LONG).show();
}
return childPosition;
}
public View getChildView1(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
return parent;
}
#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.child_item, null);
}
TextView txtListChild = (TextView) convertView.findViewById(R.id.TextView_Projectdetails);
TextView txtOneListChild = (TextView)convertView.findViewById(R.id.textOne);
TextView txtTwoListChild = (TextView)convertView.findViewById(R.id.textTwo);
TextView txtThreeListChild = (TextView)convertView.findViewById(R.id.textThree);
TextView txtFourListChild = (TextView)convertView.findViewById(R.id.textFour);
TextView txtFiveListChild = (TextView)convertView.findViewById(R.id.textFive);
txtListChild.setText(childText);
txtOneListChild.setText(childText);
txtTwoListChild.setText(childText);
txtThreeListChild.setText(childText);
txtFourListChild.setText(childText);
txtFiveListChild.setText(childText);
Button btnAssgnTask = (Button)convertView.findViewById(R.id.button_EditedTask);
btnAssgnTask.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Button btnViewTask = (Button)convertView.findViewById(R.id.buttonViewTask);
btnViewTask.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
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 ParentClickStatus;
}
#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;
}
}
}
Thanks in Advance.
your problem is here:
#Override
public int getGroupCount() {
return ParentClickStatus;
}
as you extends BaseExpandableListAdapter, getChildrenCount and getGroupCount handle number of your view and as ParentClickStatus is equal to -1 getGroupView never called
solution
you need return group row number that you have, so change your code with:
#Override
public int getGroupCount() {
return _listDataHeader.size();
}
for an example you can see section 15. Implementing an expandable ListView
UPDATE
you need change your constructor too:
public Myexpandable_ListAdapter(Context context,
List<? extends Map<String, ?>> groupData,
int expandedGroupLayout,
String[] groupFrom, int[] groupTo,
List<? extends List<? extends Map<String, ?>>> childData,
int childLayout, String[] childFrom,
int[] childTo) {
super();
// TODO Auto-generated constructor stub
}
you passed your data to here, but you don't set to any local data, for example you tried to use _listDataChild in getChild method, but you not initialize that at all, you need initialize that in constructor with your data that passed here.

Categories