I'd like to make expandable listview in android of product's list which grouped by the category. I'm using phpmyadmin as my database. How can I show the child based on their categories?
I am using JSONParser & Php code here.
Category 1
- Product A
- Product B
Category 2
- Product C
- Product D
This is the php code for show the header (category)
<?php
include("koneksi.php");
$q = mysql_query('select * from kategori_barang');
$v = '{"info" : [';
while($r=mysql_fetch_array($q))
{
$ob = array("<br>","<b>","</b>");
if(strlen($v)<12)
{
$v .= '{"id_kat" : "'.$r['id_kat'].'", "kat_barang" : "'.$r['kat_barang'].'"}';
}
else
{
$v .= '{"id_kat" : "'.$r['id_kat'].'", "kat_barang" : "'.$r['kat_barang'].'"}';
}
}
$v .= ']}';
echo $v;
?>
Here is my database
`product_id` int(4) NOT NULL AUTO_INCREMENT,
`cat_id` int(4) NOT NULL DEFAULT '0',
`subcat_id` int(4) NOT NULL DEFAULT '0',
`product_name` varchar(50) NOT NULL DEFAULT '',
`product_price` int(8) NOT NULL DEFAULT '0',
`product_weight` int(4) NOT NULL DEFAULT '0',
`product_weight_unit` varchar(10) NOT NULL DEFAULT '',
`product_price_unit` varchar(10) NOT NULL DEFAULT '',
`product_image` varchar(250) DEFAULT NULL,
`product_in_stock` int(8) DEFAULT NULL,
Here is my adapter
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 childPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
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.lblItem);
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() {
// TODO Auto-generated method stub
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return 0;
}
#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 lblHeader = (TextView) convertView
.findViewById(R.id.lblHeader);
lblHeader.setTypeface(null, Typeface.BOLD);
lblHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isChildSelectable(int arg0, int arg1) {
// TODO Auto-generated method stub
return true;
}
and here is my mainactivity
public class MainActivity extends Activity {
String link_url = "";
String [] str=null;
public static final String AR_ID_KAT = "id_kat";
public static final String AR_KAT_BARANG = "kat_barang";
JSONArray str_login = null;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<HashMap<String, String>> daftar_buku = new ArrayList<HashMap<String, String>>();
ProgressDialog mProgressDialog;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
ArrayList<HashMap<String, String>> arraylist;
HashMap<String, List<String>> listDataChild;
String id_kat, kat_barang;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview 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;
}
});
// Listview Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Sharani Designs");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
/*arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
jsonobject = JSONParser
.getJSONfromURL("http://api.androidhive.info/contacts/");
*/
JSONParser jParser = new JSONParser();
link_url = "http://10.0.2.2/login/test_kat.php";
JSONObject json = jParser.AmbilJson(link_url);
try {
str_login = json.getJSONArray("info");
for (int i = 0; i < str_login.length(); i++) {
JSONObject ar = str_login.getJSONObject(i);
String id = ar.getString(AR_ID_KAT);
String isb = ar.getString(AR_KAT_BARANG);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(AR_ID_KAT, id);
map.put(AR_KAT_BARANG, isb);
daftar_buku.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
mProgressDialog.dismiss();
}
}
Related
how to convert expandable list view to list view with recycle list view as child in android
and display like google play store..
how to convert expandable list view to list view.....
i need your help to reovle my problem..advance thanks
sample
here is json:
{
"category": [
{
"id": "23",
"category_name": "Sports",
"category_image": "avenger,jpg",
"sub_category": [
{
"id": "6",
"name": "Cricket"
},
{
"id": "9",
"name": "footbal"
}
]
},
{
"id": "24",
"category_name": "General Knowledge",
"category_image": "|avengers.jpg",
"sub_category": [
{
"id": "5",
"name": "Science"
}
]
},
]
}
here is ExpandableListAdapter:
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 JsonParser:
public class JSONParser {
public JSONParser() {
}
public String makeServiceCall(String serviceUrl) {
Boolean registered = false;
StringBuffer response = new StringBuffer();
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(serviceUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
registered = true;
// Get Response
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
/* ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
response.append("Error");*/
}
Log.v("Response:", response.toString());
return response.toString();
}
}
Here Is Main Actrivity:
public class Main2Activity extends AppCompatActivity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private ProgressDialog mprocessingdialog;
private static String url = "http://10.0.2.2/quiz/13.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
mprocessingdialog = new ProgressDialog(this);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
new DownloadJason().execute();
}
private class DownloadJason extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// Showing Progress dialog
mprocessingdialog.setTitle("Please Wait..");
mprocessingdialog.setMessage("Loading");
mprocessingdialog.setCancelable(false);
mprocessingdialog.setIndeterminate(false);
mprocessingdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
JSONParser jp = new JSONParser();
String jsonstr = jp.makeServiceCall(url);
Log.d("Response = ", jsonstr);
if (jsonstr != null) {
// For Header title Arraylist
listDataHeader = new ArrayList<String>();
// Hashmap for child data key = header title and value = Arraylist (child data)
listDataChild = new HashMap<String, List<String>>();
try {
JSONObject jsonObject = new JSONObject(jsonstr);
JSONArray dataArray = jsonObject.getJSONArray("category");
for(int i=0;i<dataArray.length();i++)
{
JSONObject internalObject = dataArray.getJSONObject(i);
listDataHeader.add(internalObject.getString("category_name"));
JSONArray jsonArray = internalObject.getJSONArray("sub_category");
ArrayList<String> subCategoryList = new ArrayList<>();
for(int j=0;j<jsonArray.length();j++)
{
subCategoryList.add(jsonArray.getJSONObject(j).getString("name"));
}
listDataChild.put(listDataHeader.get(i),subCategoryList);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),
"Please Check internet Connection", Toast.LENGTH_SHORT)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mprocessingdialog.dismiss();
//call constructor
listAdapter = new ExpandableListAdapter(getApplicationContext(), listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}
}
Hope you can help.
I need to add a variable to a button which I make visible depending on a value which may or may not be present in the database. This is working fine.
But I now need to add the id to this button.
Please see below.
ExpandableListView.java
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);
}
final TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem);
//listDataChild
final Button markAsBoughtButton = convertView.findViewById(R.id.BtnToClick);
// set 'Mark as bought' button to visible
if(childText.contains("bought by")){
markAsBoughtButton.setVisibility(View.GONE);
}else{
markAsBoughtButton.setVisibility(View.VISIBLE);
}
markAsBoughtButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
View parentRow = (View) view.getParent();
ListView listView = (ListView) parentRow.getParent();
final int pos = listView.getPositionForView(parentRow);
Toast.makeText(_context, "Bought! " + " Position " + pos, Toast.LENGTH_LONG).show();
}
});
txtListChild.setText(childText);
return convertView;
}
etc.
MainActivity.java
public class MainActivity extends ProfileActivity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private ProgressDialog mprocessingdialog;
private static String url = "http://www.xxx/xxxx/xxxx/xxxx.php";
public static String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// added to include custom icon
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(ic_launcher);
mprocessingdialog = new ProgressDialog(this);
// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
new DownloadJason().execute();
}
/*
* Preparing the list data
*/
private class DownloadJason extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Showing Progress dialog
mprocessingdialog.setTitle("Please Wait..");
mprocessingdialog.setMessage("Loading");
mprocessingdialog.setCancelable(false);
mprocessingdialog.setIndeterminate(false);
mprocessingdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
JSONParser jp = new JSONParser();
String jsonstr = jp.makeServiceCall(url);
Log.d("Response = ", jsonstr);
if (jsonstr != null) {
// For Header title Arraylist
listDataHeader = new ArrayList<String>();
// Hashmap for child data key = header title and value = Arraylist (child data)
listDataChild = new HashMap<String, List<String>>();
try {
JSONObject jobj = new JSONObject(jsonstr);
JSONArray jarray = jobj.getJSONArray("presents_db");
for (int hk = 0; hk < jarray.length(); hk++) {
JSONObject d = jarray.getJSONObject(hk);
// Adding Header data
listDataHeader.add(d.getString("name") + "'s presents are: ");
// Adding child data for members
List<String> members = new ArrayList<String>();
JSONArray xarray = d.getJSONArray("presents_list");
for (int i = 0; i < xarray.length(); i++) {
JSONObject a = xarray.getJSONObject(i);
String id = a.getString("id");
String present = a.getString("present");
if("".equals(a.getString("bought_by"))) {
members.add(id + " " + present);
}else{
members.add(id + " " + present + "\r\n bought by: " + a.getString("bought_by"));
}
}
// Header into Child data
listDataChild.put(listDataHeader.get(hk), members);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),"Please Check internet Connection", Toast.LENGTH_SHORT).show();
}
return null;
}
Apologies for the bad coding but I am new to java and it's a steep learing curve.
Thanks for your help!
You can use setTag() and getTag()
//Set tag
button.setTag(position);
//Get Tag
new OnClickListener() {
#Override
public void onClick(View v) {
int pos = v.getTag();
//Get Tag work on view like button
}
What is the main purpose of setTag() getTag() methods of View?
In my app I am trying to save data using ArrayList<HashMap<String, String>>
below is my code:
JsonArrayRequest req = new JsonArrayRequest(Constants.DARSHAN_URL+Constants.MAIN_CATEGORY,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String material_id = person.getString("material_id");
String material_desc = person.getString("material_desc");
HashMap<String, String> maim_category_array = new HashMap<>();
maim_category_array.put("material_id", material_id);
maim_category_array.put("material_desc", material_desc);
categoryName.add(maim_category_array);
}
adapter = new GridviewAdapter(MainCategoryActivity.this, categoryName);
grid.setAdapter(adapter);
And below is my GridViewCoustomAdapter:
public class GridviewAdapter extends BaseAdapter
{
private ArrayList<HashMap<String, String>> listCountry;
private Activity activity;
public GridviewAdapter(Activity activity, ArrayList<HashMap<String, String>> listCountry) {
super();
this.listCountry = listCountry;
this.activity = activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listCountry.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listCountry.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public TextView txtViewTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.button_layout, null);
view.txtViewTitle = (TextView) convertView.findViewById(R.id.btn_select);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map = new HashMap<String, String>();
map = listCountry.get(position);
view.txtViewTitle.setText(map.get("material_desc"));
return convertView;
}}
Now I want to get the material_Id to send to next activity. i.e. I want to get matrial_Id onItemClick of gridview
for example:
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Toast.makeText(MainCategoryActivity.this, adapter.getItem(position), Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainCategoryActivity.this, ProductNameActivity.class);
i.putExtra("MATERIAL_ID", <material_id>);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
How can I do this??
Please help!!
In onItemClick
HashMap<String, String> map = (HashMap<String, String>)arg0.getItemAtPosition(position);
Then
String id = map.get("material_id");
Below is my code for base adapter. I will be using this class as an adapter for a ListView.
public class CustombaseAdapterTxnCartSelect extends BaseAdapter
{
private Context mContext;
private List<RowItemTxnCartSelect> mRowItems;
TextView standDesc, seats, totalTicketTariff, eventDesc;
public CustombaseAdapterTxnCartSelect(Context context, List<RowItemTxnCartSelect> rowItems) {
mContext = context;
mRowItems = rowItems;
}
#Override
public int getCount() {
return mRowItems.size();
}
#Override
public Object getItem(int position) {
return mRowItems.get(position);
}
#Override
public long getItemId(int position) {
return mRowItems.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = null;
LayoutInflater mInflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflator.inflate(R.layout.event_layout_txn__cart_select, null);
standDesc = (TextView) convertView.findViewById(R.id.textViewTxnCartSelectStandDesc);
seats = (TextView) convertView.findViewById(R.id.textViewTxnCartSelectSeats);
totalTicketTariff = (TextView) convertView.findViewById(R.id.textViewTxnCartSelectTotalTicketTariff);
eventDesc = (TextView) convertView.findViewById(R.id.textViewEventDesc);
RowItemTxnCartSelect row = (RowItemTxnCartSelect) getItem(position);
standDesc.setText(row.getmStandDesc());
seats.setText(row.getmSeats());
totalTicketTariff.setText(row.getMtotalTicketTariff());
eventDesc.setText(row.getmEventDesc());
return convertView;
}
}
I just want to convert it into an expandable list view I'm not clear about what all I have to add.
maybe you could something like this :
public class FevList extends ExpandableListActivity {
String title;
String url;
SQLiteDatabase database;
DbUtil db;
HashMap<String, String> map = new HashMap<String, String>();
ArrayList<HashMap<String, String>> subjectList = new ArrayList<HashMap<String, String>>();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.exlist);
db = new DbUtil();
database = db.openConnection(this);
// Thread for getting values of title from DataBase.
SimpleExpandableListAdapter expListAdapter = new SimpleExpandableListAdapter(
this, createGroupList(), R.layout.group_row,
new String[] { "subject" }, new int[] { R.id.row_name },
createChildList(), R.layout.child_row,
new String[] { "title" }, new int[] { R.id.grp_child });
setListAdapter(expListAdapter);
registerForContextMenu(getExpandableListView());
} catch (Exception e) {
e.printStackTrace();
}
}
// code for adapter
/* Creating the Hashmap for the row */
ArrayList> result = new ArrayList>();
#SuppressWarnings("unchecked")
private List createGroupList() {
// write your code here.
return (List) result;
}
/* creatin the HashMap for the children */
#SuppressWarnings("unchecked")
private List createChildList() {
// write your code here.
return result;
}
public void onContentChanged() {
System.out.println("onContentChanged");
super.onContentChanged();
}
/* This function is called on each child click */
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// write your code here.
return true;
}
/* This function is called on expansion of the group */
public void onGroupExpand(int groupPosition) {
try {
System.out.println("Group exapanding Listener => groupPosition = "
+ groupPosition);
} catch (Exception e) {
System.out.println(" groupPosition Errrr +++ " + e.getMessage());
}
}
}
this is a snippet , you could refer to this
Here is an Opensource example project to demonstrate ExpandableListView. It is good example to getting started with Expandable Listviews.
Problem is with checkbox. When user click on child, app should show toast message on which child user clicked. It works fine if I click on textview of child, but when i click on checkbox, nothing heppend. Also when I click on child item, I want that my checkbox change state. Do you see something that I can't see. Here is my code for main activity
private ExpandableAdapter adapter;
private ExpandableListView expandableList;
private List<Pitanja> pitanjas = new ArrayList<Pitanja>();
private ArrayList<Pitanja> listaPitanja = new ArrayList<Pitanja>();
private List<Odgovor> odgovors = new ArrayList<Odgovor>();
public static HashMap<Integer, Integer> pitanjaa;
private Intent intent;
private ProgressDialog pDialog;
private TextView output;
private List<Ispit> ispitList;
private String pozicija;
private Button posalji;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ispit);
output = (TextView) findViewById(R.id.ispit_datum);
output.setMovementMethod(new ScrollingMovementMethod());
pitanjaa = new HashMap<Integer, Integer>();
posalji = (Button) findViewById(R.id.posaljiIspitButton);
posalji.setOnClickListener(this);
generateData();
initEx();
intent = getIntent();
RequestPackage p = new RequestPackage();
p.setUri("http://arka.foi.hr/WebDiP/2012_projekti/WebDiP2012_085/AIR/ispit.php");
p.setMethod("POST");
p.setParam("id_kolegij", intent.getStringExtra("id_predmeta"));
Log.i("Saljem podatke ", intent.getStringExtra("id_predmeta"));
MyTask task = new MyTask();
task.execute(p);
}
private void updateDisplay(){
Collections.shuffle(ispitList);
output.setText(String.valueOf(ispitList.get(0).getId()));
MyRequest task = new MyRequest();//this works fine
RequestPackage r = new RequestPackage();//works
r.setMethod("POST");//works
r.setUri("http://arka.foi.hr/WebDiP/2012_projekti/WebDiP2012_085/AIR/pitanja.php");//works
r.setParam("id_kolegij", output.getText().toString());//works
task.execute(r);
}
private void initEx(){
adapter = new ExpandableAdapter(IspitActivity.this, listaPitanja);
expandableList = (ExpandableListView) findViewById(R.id.expandableIspitListView);
expandableList.setAdapter(adapter);
for (int i=0;i<adapter.getGroupCount();i++){
expandableList.collapseGroup(i);
}
expandableList.setOnChildClickListener(new OnChildClickListener(){
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1,
int arg2, int arg3, long arg4) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Klikno si na " + adapter.getChild(arg2, arg3).getText() + " " + adapter.getChild(arg2, arg3).getTocan_netocan(), Toast.LENGTH_SHORT).show();
if (Integer.parseInt(adapter.getChild(arg2, arg3).getTocan_netocan()) == 0)
pitanjaa.put(arg2, arg3);
Log.i("pitanja koja si odgovorio su", pitanjaa.toString());
adapter.getChild(arg2, arg3).setSelected(true);
return true;
}
});
}
private void generateData(){
Pitanja p;
for (int i=0;i<pitanjas.size();i++){
ArrayList<Odgovor> od = new ArrayList<Odgovor>();
for (int z=0;z<odgovors.size();z++){
if (odgovors.get(z).getId_pitanja().contains(String.valueOf(pitanjas.get(i).getId()))){
od.add(odgovors.get(z));
}
}
pozicija = pitanjas.get(i).getText();
p = new Pitanja(i, pozicija, od);
listaPitanja.add(p);
}
}
private class MyTask extends AsyncTask<RequestPackage, String, List<Ispit>>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(IspitActivity.this);
pDialog.setMessage("Dobavljam podatke...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected List<Ispit> doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
ispitList = JSONParser.parseIspit(content.substring(1, content.length()-1));
Log.i("Parsirano izgleda sljedeci", content.substring(1, content.length()-1));
return ispitList;
}
#Override
protected void onPostExecute(List<Ispit> result) {
super.onPostExecute(result);
pDialog.dismiss();
updateDisplay();
}
}
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), PregledActivity.class);
startActivity(intent);
}
}
Here is my expandablelistview adapter
public class ExpandableAdapter extends BaseExpandableListAdapter{
LayoutInflater inflater;
private List<Pitanja> groups;
public ExpandableAdapter(Context context,List<Pitanja> groups) {
super();
this.groups=groups;
inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(Odgovor child,Pitanja group) {
if(!groups.contains(group)) {
groups.add(group);
}
int index=groups.indexOf(group);
ArrayList<Odgovor> ch=groups.get(index).getOdgovors();
ch.add(child);
groups.get(index).setOdgovors(ch);
}
public Odgovor getChild(int groupPosition, int childPosition) {
ArrayList<Odgovor> ch=groups.get(groupPosition).getOdgovors();
return ch.get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Odgovor> ch=groups.get(groupPosition).getOdgovors();
return ch.size();
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
Odgovor child= (Odgovor) getChild(groupPosition,childPosition);
TextView childName=null;
CheckBox cb = null;
if(convertView==null) {
convertView=inflater.inflate(R.layout.child_item, null);
}
childName=(TextView) convertView.findViewById(R.id.textview_child_item);
childName.setText(child.getText());
cb = (CheckBox) convertView.findViewById(R.id.checkbox_child_item);
if (child.isSelected())
cb.setChecked(true);
return convertView;
}
public Pitanja getGroup(int groupPosition) {
return groups.get(groupPosition);
}
public int getGroupCount() {
return groups.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
TextView groupName = null;
Pitanja group=(Pitanja) getGroup(groupPosition);
if(convertView==null) {
convertView=inflater.inflate(R.layout.parent_item, null);
}
groupName=(TextView) convertView.findViewById(R.id.parent_item);
groupName.setText(group.getText());
return convertView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
my child view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/checkbox_child_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />
<TextView
android:id="#+id/textview_child_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
If I changle focusable of my checkbox, it doesn't work too. Someone have idea
The CheckBox will consume the click event before passing it on to the ExpandableListView click event. You'll need to manually attached a click listener to the CheckBox in the getChildView() method if you want to see those click events.