Expand listview based on child count - java

I need some help. I am trying to implement the Expandable list view. My problem is that when there are more than 2 children then only group must expand if not text view and button visible on the group layout. Please go through my code and the attached Image. The textview and button are visible when there are more than 2 children also.
Screenshot of the menu
Menu.java
public class SubMenu extends BaseActivity {
String item;
ExpandableListView sec;
Toolbar carttoolbar;
private int lastExpandedPosition = -1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sub_menu);
carttoolbar = (Toolbar) findViewById(R.id.carttoolbar);
setSupportActionBar(carttoolbar);
assert getSupportActionBar() != null;
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
String catname = getIntent().getStringExtra("CatName");
getSupportActionBar().setTitle(catname);
sec = (ExpandableListView) findViewById(R.id.seondlst);
sec.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
sec.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
Intent hello = getIntent();
item = hello.getStringExtra("Catergory");
loaditems();
}
private void loaditems() {
String url = Constant.commonurlyell + "data_standard_item_ind_new.php?rname=standardtakeaway&id=" + item;
Log.d("ITems", url);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
JsonObjectRequest arrayRequest = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ArrayList<Subitem_base> list = new ArrayList<Subitem_base>();
ArrayList<Subitem_base_child> ch_list = new ArrayList<Subitem_base_child>();
try {
JSONArray itemsarray = response.getJSONArray("items");
Map<Integer, ArrayList<Subitem_base_child>> ch_lists = new HashMap<Integer, ArrayList<Subitem_base_child>>();
for (int i = 0; i < itemsarray.length(); i++) {
ch_list = new ArrayList<Subitem_base_child>();
JSONObject itemsobj = itemsarray.getJSONObject(i);
Subitem_base subitem = new Subitem_base();
subitem.setGroupitemname(itemsobj.getString("BaseName"));
JSONArray subitemsarray=itemsobj.getJSONArray("subitems");
for (int j = 0; j <subitemsarray.length() ; j++) {
JSONObject subitemsobj=subitemsarray.getJSONObject(j);
Subitem_base_child subitembase=new Subitem_base_child();
subitembase.setChilditemname(subitemsobj.getString("SubItemdesc"));
String pricevalue = "£";
subitembase.setChilditemprice(pricevalue.concat(subitemsobj.getString("SubItemprice")));
ch_list.add(subitembase);
}
ch_lists.put(i, ch_list);
subitem.setItems(ch_lists.get(i));
list.add(subitem);
}
SubItem_ExpandAdapter subexpand = new SubItem_ExpandAdapter(getApplicationContext(), list,SubMenu.this);
int childCount=sec.getChildCount();
Log.d("Std", String.valueOf(childCount));
sec.setAdapter(subexpand);
subexpand.notifyDataSetChanged();
progressDialog.hide();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("SecondleveError", String.valueOf(error));
}
});
arrayRequest.setRetryPolicy(new DefaultRetryPolicy(50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(arrayRequest);
}
}
MenuAdapter.java
public class SubItem_ExpandAdapter extends BaseExpandableListAdapter {
Context subcontext;
private ArrayList<Subitem_base> subitem_bases;
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
String itembasename, itemde, subtmsub, subitempri;
private Activity parentActivity;
public SubItem_ExpandAdapter(Context subcontext, ArrayList<Subitem_base> subitem_bases, Activity parentactivity) {
this.subcontext = subcontext;
this.subitem_bases = subitem_bases;
this.parentActivity=parentactivity;
}
static class Groupname {
private TextView group_name;
private TextView groupitem_price;
private Button grouporder;
private ImageView droparrow;
}
static class Childnames {
private TextView item_name;
private TextView item_price;
private Button order;
}
#Override
public int getGroupCount() {
return subitem_bases.size();
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Subitem_base_child> subitem_base_children = subitem_bases.get(groupPosition).getItems();
return subitem_base_children.size();
}
#Override
public Object getGroup(int groupPosition) {
return subitem_bases.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<Subitem_base_child> subitem_base_children = subitem_bases.get(groupPosition).getItems();
return subitem_base_children.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
Groupname groupname;
if (convertView == null) {
convertView = LayoutInflater.from(subcontext).inflate(R.layout.group_item, parent, false);
groupname = new Groupname();
groupname.group_name = (TextView) convertView.findViewById(R.id.group_name);
groupname.groupitem_price = (TextView) convertView.findViewById(R.id.groupitem_price);
groupname.grouporder = (Button) convertView.findViewById(R.id.grouporder);
groupname.droparrow = (ImageView) convertView.findViewById(R.id.droparrow);
convertView.setTag(groupname);
} else {
groupname = (Groupname) convertView.getTag();
}
Subitem_base groupitem = subitem_bases.get(groupPosition);
groupname.group_name.setText(groupitem.getGroupitemname());
if (isExpanded){
String[] elements = {groupitem.getGroupitemname() };
for (String s: elements) {
itembasename=s;
}
}
if (getChildrenCount(groupPosition)>=2) {
Log.d("Std", "called");
}else {
groupname.groupitem_price.setVisibility(View.VISIBLE);
groupname.droparrow.setVisibility(View.GONE);
groupname.grouporder.setVisibility(View.VISIBLE);
}
return convertView;
}
#Override
public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final Childnames childname;
if (convertView == null) {
convertView = LayoutInflater.from(subcontext).inflate(R.layout.child_item, parent, false);
childname = new Childnames();
childname.item_name = (TextView) convertView.findViewById(R.id.item_name);
childname.item_price = (TextView) convertView.findViewById(R.id.item_price);
childname.order = (Button) convertView.findViewById(R.id.order);
convertView.setTag(childname);
}else {
childname= (Childnames) convertView.getTag();
}
Subitem_base_child childitem = (Subitem_base_child) getChild(groupPosition, childPosition);
if (childitem.getChilditemname().isEmpty()){
childname.item_name.setVisibility(View.GONE);
}else {
childname.item_name.setText(childitem.getChilditemname());
}
childname.item_price.setText(childitem.getChilditemprice());
loginPreferences = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
final String status = loginPreferences.getString("Status", "");
if (status.equals("0")) {
childname.order.setBackgroundResource(R.drawable.cart_disable);
}else {
childname.order.setBackgroundResource(R.drawable.cart_button);
}
childname.order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (status.equals("0")) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(parentActivity);
SharedPreferences customerid = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String opentimes = customerid.getString("open", "");
alertDialogBuilder.setMessage(opentimes);
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
alertDialogBuilder.setCancelable(true);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
String poundre = childname.item_price.getText().toString();
subtmsub=childname.item_name.getText().toString();
subitempri = poundre.replace("£", "");
addcart();
}
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private void addcart(){
loginPreferences = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
SharedPreferences customerid = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPreferences.edit();
String customid = customerid.getString("customerid", "");
String cartdetails = itembasename + " " + subtmsub;
String cartspacong = cartdetails.replace(" ", "$");
cartspacong = cartspacong.replace("&", "and");
String addcarturl = Constant.commonurltake + "cart_process.php?userid=" + customid + "&Item=" + cartspacong + "&Itemcount=1&price=" + subitempri + "&page=items";
Log.d("Cart", addcarturl);
JsonArrayRequest cartreq = new JsonArrayRequest(Request.Method.POST, addcarturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject cartobj = response.getJSONObject(i);
String cartnumber = cartobj.getString("count");
loginPrefsEditor.putString("Count", cartnumber);
BaseActivity.cartnumber.setVisibility(View.VISIBLE);
BaseActivity.cartnumber.setText(cartnumber);
loginPrefsEditor.apply();
if (cartobj.has("message")) {
Toast carttost = Toast.makeText(subcontext, cartobj.getString("message"), Toast.LENGTH_SHORT);
carttost.setGravity(Gravity.CENTER, 0, 0);
carttost.show();
} else {
Toast carttost = Toast.makeText(subcontext, "Product Added To Cart", Toast.LENGTH_SHORT);
carttost.setGravity(Gravity.CENTER, 0, 0);
carttost.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(subcontext, "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
}

Related

Updated data for clicked row but scroll down the listview some row will also updated

I'm trying to update data for clicked row with dialog box. I can updated but when i scroll down some row will also updated. Then, when i scroll up again the data will random updated to other row.
Below is my adapter code:
public class ViewHolder {
TextView productid, productname, pcs, cs;
ImageView dist;
}
public List<Product_List> parkingList;
public Context context;
ArrayList<Product_List> arrayList;
private MyAppAdapter(List<Product_List> apps, Context context) {
this.parkingList = apps;
this.context = context;
arrayList = new ArrayList<Product_List>();
arrayList.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View rowView = convertView;
final MyAppAdapter.ViewHolder viewHolder;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.productlist, parent, false);
viewHolder = new MyAppAdapter.ViewHolder();
viewHolder.productid = (TextView) rowView.findViewById(R.id.productid);
viewHolder.productname = (TextView) rowView.findViewById(R.id.productname);
viewHolder.pcs = (TextView) rowView.findViewById(R.id.pcs);
viewHolder.cs = (TextView) rowView.findViewById(R.id.cs);
viewHolder.dist = (ImageView) rowView.findViewById(R.id.dist);
rowView.setTag(viewHolder);
} else {
viewHolder = (MyAppAdapter.ViewHolder) convertView.getTag();
}
viewHolder.productid.setText(parkingList.get(position).getInvtID() + "");
viewHolder.productname.setText(parkingList.get(position).getDescr() + "");
final String a = viewHolder.productid.getText().toString();
final String b = viewHolder.productname.getText().toString();
if ( position % 2 == 0) {
rowView.setBackgroundColor(Color.parseColor("#FFFFFF"));
} else {
rowView.setBackgroundColor(Color.parseColor("#ECEAEA"));
}
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog dialog = new Dialog(context);
dialog.setTitle("Inventory Checking");
dialog.setContentView(R.layout.inventory);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
final TextView productids = (TextView) dialog.findViewById(R.id.productids);
productids.setText(a);
final TextView productdesc = (TextView) dialog.findViewById(R.id.productdesc);
productdesc.setText(b);
final EditText pcss = (EditText) dialog.findViewById(R.id.pcss);
final EditText css = (EditText) dialog.findViewById(R.id.css);
final RadioButton btnyes = (RadioButton) dialog.findViewById(R.id.btnyes);
final RadioButton btnno = (RadioButton) dialog.findViewById(R.id.btnno);
btnno.setChecked(true);
Button btnsave = (Button) dialog.findViewById(R.id.btnsave);
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.pcs.setText(pcss.getText().toString());
viewHolder.cs.setText(css.getText().toString());
if (btnyes.isChecked()) {
viewHolder.dist.setImageResource(R.drawable.done);
} else {
viewHolder.dist.setImageResource(R.drawable.no);
}
notifyDataSetChanged();
dialog.dismiss();
}
});
dialog.show();
}
});
return rowView;
}
}
This is my adapter code.
String msg="Found";
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(InventoryChecking1.this, "Synchronising",
"Listview Loading! Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) {
try {
Connection conn = connectionClass.CONN();
if (conn == null) {
success = false;
} else {
String query = "SELECT * FROM Inventory";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
while (rs.next()) {
try {
if (rs.getString("Status").equals("A") || rs.getString("Status").equals("AC")) {
itemsArrayList.add(new Product_List(rs.getString("InvtID"), rs.getString("Descr"), rs.getString("Brand"),
rs.getString("Category")));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
// Toast.makeText(SellerActivity.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemsArrayList, InventoryChecking1.this);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
Change data in list instead of UI Views just change in list and notify
the adapter:
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Product_List product_list = new Product_List(pcss.getText().toString(),css.getText().toString());
parkingList.set( position,product_list );
notifyDataSetChanged();
dialog.dismiss();
}
});

Spinner In Custom ListView Randomly Changed When Scrolling

I Just need to fix the value inside Spinner when i select some value and SetEnabled True/False when i checked the CheckBox.
For example when i check the chekcbox, the spinner will be enabled and do the opposite when i uncheck the checkbox.
However it will changing randomly when i just scrolling.
This my code :
CustomListView.java
class CustomListView extends BaseAdapter {
private ArrayList<ListItem2> listData;
private LayoutInflater layoutInflater;
private Context context;
public CustomListView adapter = this;
String jmlCmbSiap;
ArrayList<String> a = new ArrayList<>();
public CustomListView(Context context, ArrayList<ListItem2> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
newsItem = listData.get(position);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_detail_order, null);
holder = new ViewHolder();
newsItem.setAdapter(Integer.parseInt(newsItem.getJumlah()));
holder.txtBarang = (TextView) convertView.findViewById(R.id.txtBarang);
holder.txtJumlah = (TextView) convertView.findViewById(R.id.txtJumlah);
holder.txtBox = (TextView) convertView.findViewById(R.id.txtBoxes);
holder.cmbSiap = (Spinner) convertView.findViewById(R.id.cmbSiap);
holder.cmbSiap.setAdapter(newsItem.getAdapter());
holder.thumbImage = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.chkOk = (CheckBox) convertView.findViewById(R.id.chkOk);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Picasso
.with(context)
.load(newsItem.getImg())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(holder.thumbImage);
holder.txtBarang.setText(newsItem.getNamaProduk().toUpperCase());
holder.txtJumlah.setText(newsItem.getJumlah().toUpperCase());
holder.cmbSiap.setSelection(Integer.parseInt(newsItem.getJumlah()));
holder.cmbSiap.setEnabled(newsItem.getcmbSiap());
holder.txtBox.setEnabled(newsItem.gettxtBox());
holder.cmbSiap.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
jmlCmbSiap = parent.getItemAtPosition(position).toString();
newsItem.setJumlah(jmlCmbSiap);
holder.cmbSiap.setSelection(Integer.parseInt(newsItem.getJumlah()));
System.out.println("JML : " + newsItem.getJumlah());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
holder.chkOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (newsItem.getchkOk() == false) {
newsItem.setcmbSiap(true);
newsItem.setchkOk(true);
newsItem.settxtBox(true);
holder.cmbSiap.setEnabled(true);
holder.chkOk.setChecked(true);
txtBox.setEnabled(true);
numberChecked = numberChecked + 1;
idChkOk.add(position);
System.out.println("Chk : " + idChkOk);
} else {
numberChecked = numberChecked - 1;
newsItem.setcmbSiap(false);
newsItem.setchkOk(false);
holder.cmbSiap.setEnabled(false);
holder.chkOk.setChecked(false);
if (numberChecked == 0) {
newsItem.settxtBox(false);
txtBox.setEnabled(false);
}
idChkOk.remove(position);
System.out.println("Chk : " + idChkOk);
}
}
});
cmdPak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a.clear();
for (int i = 0; i < listData.size(); i++)
{
newsItem = listData.get(i);
a.add(newsItem.getJumlah().toString());
}
System.out.println("Pak : " + a);
}
});
return convertView;
}
class ViewHolder {
TextView txtBarang,txtJumlah,txtBox;
Spinner cmbSiap;
ImageView thumbImage;
CheckBox chkOk;
}
}
ListItem2.java
class ListItem2 {
private String shipment;
private String truck;
private String transporter;
private String tanggal;
private String order;
private String nilai;
private String alamat;
private String status;
private String jumlah;
private String namaProduk;
private String img;
private String sopir;
private String jumlahTerima;
private String alasan;
private String orderTemp;
private Boolean chkOk;
private Boolean cmbSiap;
private Boolean txtBox;
private ArrayAdapter<CharSequence> adapter;
private ArrayList<String> array = new ArrayList<String>();
public void setAdapter(Integer jml)
{
for (int i = 0; i<= jml; i++) {
array.add(String.valueOf(i));
}
adapter = new ArrayAdapter(DetailOrder.this,android.R.layout.simple_spinner_item,array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
public ArrayAdapter<CharSequence> getAdapter()
{
return adapter;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public String getNilai() {
return nilai;
}
public void setNilai(String nilai) {
this.nilai = nilai;
}
public String getKodeProduk() {
return nilai;
}
public void setKodeProduk(String nilai) {
this.nilai = nilai;
}
public String getNamaProduk() {
return namaProduk;
}
public void setNamaProduk(String namaProduk) {
this.namaProduk = namaProduk;
}
public String getJumlah() {
return jumlah;
}
public void setJumlah(String jumlah) {
this.jumlah = jumlah;
}
public Boolean getchkOk() {
return chkOk;
}
public void setchkOk(Boolean chkOk) {
this.chkOk = chkOk;
}
public Boolean getcmbSiap() {
return cmbSiap;
}
public void setcmbSiap(Boolean cmbSiap) {
this.cmbSiap = cmbSiap;
}
public Boolean gettxtBox() {
return txtBox;
}
public void settxtBox(Boolean txtBox) {
this.txtBox = txtBox;
}
}
Could you lend me a hand ?
Update :
chkAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View views;
CheckBox chkOkx;
Spinner cmbSiap;
for (int i = 0; i < jArray; i++) {
final ListItem2 newsItem = listData.get(i);
views = listView.getChildAt(i);
if (views == null) {
return;
} else {
chkOkx = (CheckBox) views.findViewById(R.id.chkOk);
cmbSiap = (Spinner) views.findViewById(R.id.cmbSiap);
if (chkOkx.isChecked()) {
newsItem.setchkOk(true);
newsItem.setcmbSiap(true);
chkOkx.setChecked(newsItem.getchkOk());
cmbSiap.setEnabled(newsItem.getcmbSiap());
} else {
newsItem.setchkOk(false);
newsItem.setcmbSiap(false);
chkOkx.setChecked(newsItem.getchkOk());
cmbSiap.setEnabled(newsItem.getcmbSiap());
}
idChkOk.add(i);
}
}
if (chkAll.isChecked()) {
txtBox.setEnabled(true);
numberChecked = 0;
} else {
txtBox.setEnabled(false);
numberChecked = listviewChild;
}
listView.invalidateViews();
}
});
In ListView when you scroll, the views are destroyed and re-created. To overcome the issue you need to preserve both of the checkbox status and spinner item's value.
For the checkbox, save the checked status from setOnClickListener inside a boolean array,
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
} else {
checkBoxState[position] = false;
}
The boolean array should like this,
private boolean[] checkBoxState;
Later on getView() apply the check/uncheck status of each checkbox items based on the array
holder.checkBox.setChecked(checkBoxState[position]);
Similarly to save the spinner data, create a Hashmap
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
and save the spinner data once it's selected from the setOnItemSelectedListener
myMap.put(position, pos);
Later restore the spinner selection position from the saved data,
if (myMap.containsKey(position)) {
viewHolder.spinner.setSelection(myMap.get(position));
}
Full code,
class CustomListView extends BaseAdapter {
private ArrayList<ListItem2> listData;
private LayoutInflater layoutInflater;
private Context context;
public CustomListView adapter = this;
String jmlCmbSiap;
ArrayList<String> a = new ArrayList<>();
private boolean[] checkBoxState;
private Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
public CustomListView(Context context, ArrayList<ListItem2> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
checkBoxState = new boolean[listData.size()];
this.context = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
newsItem = listData.get(position);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_detail_order, null);
holder = new ViewHolder();
newsItem.setAdapter(Integer.parseInt(newsItem.getJumlah()));
holder.txtBarang = (TextView) convertView.findViewById(R.id.txtBarang);
holder.txtJumlah = (TextView) convertView.findViewById(R.id.txtJumlah);
holder.txtBox = (TextView) convertView.findViewById(R.id.txtBoxes);
holder.cmbSiap = (Spinner) convertView.findViewById(R.id.cmbSiap);
holder.cmbSiap.setAdapter(newsItem.getAdapter());
holder.thumbImage = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.chkOk = (CheckBox) convertView.findViewById(R.id.chkOk);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setChecked(checkBoxState[position]);
if (checkBoxState[position])
{
holder.chkOk.setChecked(true);
newsItem.setcmbSiap(true);
newsItem.settxtBox(true);
holder.cmbSiap.setEnabled(true);
holder.cmbSiap.setClickable(true);
txtBox.setEnabled(true);
}
else
{
holder.chkOk.setChecked(false);
newsItem.setcmbSiap(false);
newsItem.settxtBox(false);
holder.cmbSiap.setEnabled(false);
holder.cmbSiap.setClickable(false);
txtBox.setEnabled(false);
}
Picasso
.with(context)
.load(newsItem.getImg())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(holder.thumbImage);
holder.txtBarang.setText(newsItem.getNamaProduk().toUpperCase());
holder.txtJumlah.setText(newsItem.getJumlah().toUpperCase());
holder.cmbSiap.setSelection(Integer.parseInt(newsItem.getJumlah()));
holder.cmbSiap.setEnabled(newsItem.getcmbSiap());
holder.txtBox.setEnabled(newsItem.gettxtBox());
if (myMap.containsKey(position)) {
viewHolder.spinner.setSelection(myMap.get(position));
}
holder.cmbSiap.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
jmlCmbSiap = parent.getItemAtPosition(position).toString();
newsItem.setJumlah(jmlCmbSiap);
myMap.put(position, pos);
System.out.println("JML : " + newsItem.getJumlah());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
holder.chkOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//is chkOk checked?
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
viewHolder.spinner.setEnabled(true);
viewHolder.spinner.setClickable(true);
} else {
checkBoxState[position] = false;
viewHolder.spinner.setEnabled(false);
viewHolder.spinner.setClickable(false);
}
}
});
cmdPak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a.clear();
for (int i = 0; i < listData.size(); i++)
{
newsItem = listData.get(i);
a.add(newsItem.getJumlah().toString());
}
System.out.println("Pak : " + a);
}
});
return convertView;
}
class ViewHolder {
TextView txtBarang,txtJumlah,txtBox;
Spinner cmbSiap;
ImageView thumbImage;
CheckBox chkOk;
}
}
Update:
In order to make a select all/deselect all checkbox feature,
create a boolean flag at the top of adapter's class,
boolean isCheckAll = false;
then create a toggle method,
public void toggleCheckAll() {
isCheckAll = !isCheckAll;
for (int i = 0; i < listData.size(); i++) {
if (isCheckAll) {
checkBoxState[i] = true;
notifyDataSetInvalidated();
} else {
checkBoxState[i] = false;
notifyDataSetInvalidated();
}
}
}
Now call the method from your aactivity's check all button's click,
btnCheckAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
adapter.toggleCheckAll();
}
});

Expandale list view's Child view's issue

I am working on the expandable list view with multiple group layouts but having single child as common for all the layouts but in the getChildView() method I am getting the cast error not able understand whats the reason behind please help me out friends
this error I am getting
java.lang.ClassCastException:
com.app.prominere.standardtakeout.SubItem_ExpandAdapter$Groupname
cannot be cast to
com.app.prominere.standardtakeout.SubItem_ExpandAdapter$Childnames
BaseAdapter.Java
public class SubItem_ExpandAdapter extends BaseExpandableListAdapter {
Context subcontext;
private ArrayList<Subitem_base> subitem_bases;
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
String itembasename, itemde, subtmsub, subitempri;
private Activity parentActivity;
public static final int single = 1;
public static final int two = 2;
public SubItem_ExpandAdapter(Context subcontext, ArrayList<Subitem_base> subitem_bases, Activity parentactivity) {
this.subcontext = subcontext;
this.subitem_bases = subitem_bases;
this.parentActivity = parentactivity;
}
static class Groupname {
private TextView group_name;
private TextView groupitem_price;
// private Button grouporder;
}
static class Childnames {
private TextView item_name;
private TextView item_price;
private Button order;
}
#Override
public int getGroupCount() {
return subitem_bases.size();
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Subitem_base_child> subitem_base_children = subitem_bases.get(groupPosition).getItems();
return subitem_base_children.size();
}
#Override
public Object getGroup(int groupPosition) {
return subitem_bases.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<Subitem_base_child> subitem_base_children = subitem_bases.get(groupPosition).getItems();
return subitem_base_children.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public int getGroupTypeCount() {
return 2;
}
#Override
public int getGroupType(int groupPosition) {
Subitem_base groupstype = subitem_bases.get(groupPosition);
if (groupstype.getGrpcount().equals("1")) {
return single;
} else {
return two;
}
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
Groupname groupname;
Subitem_base groupitem = subitem_bases.get(groupPosition);
int grouptype = getGroupType(groupPosition);
if (convertView == null) {
if (grouptype == single) {
convertView = LayoutInflater.from(subcontext).inflate(R.layout.groupcount_single, parent, false);
} else {
convertView = LayoutInflater.from(subcontext).inflate(R.layout.group_item, parent, false);
}
groupname = new Groupname();
groupname.group_name = (TextView) convertView.findViewById(R.id.group_name);
groupname.groupitem_price = (TextView) convertView.findViewById(R.id.groupitem_price);
// groupname.grouporder = (Button) convertView.findViewById(R.id.grouporder);
convertView.setTag(groupname);
} else {
groupname = (Groupname) convertView.getTag();
}
groupname.group_name.setText(groupitem.getGroupitemname());
groupname.groupitem_price.setText(groupitem.getGrprice());
if (isExpanded) {
String[] elements = {groupitem.getGroupitemname()};
for (String s : elements) {
itembasename = s;
}
}
return convertView;
}
#Override
public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final Childnames childname;
if (convertView == null) {
convertView = LayoutInflater.from(subcontext).inflate(R.layout.child_item, parent, false);
childname = new Childnames();
childname.item_name = (TextView) convertView.findViewById(R.id.item_name);
childname.item_price = (TextView) convertView.findViewById(R.id.item_price);
childname.order = (Button) convertView.findViewById(R.id.order);
convertView.setTag(childname);
} else {
childname = (Childnames) convertView.getTag();
}
Subitem_base_child childitem = (Subitem_base_child) getChild(groupPosition, childPosition);
if (childitem.getChilditemname().isEmpty()) {
childname.item_name.setVisibility(View.GONE);
} else {
childname.item_name.setText(childitem.getChilditemname());
}
childname.item_price.setText(childitem.getChilditemprice());
loginPreferences = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
final String status = loginPreferences.getString("Status", "");
if (status.equals("0")) {
childname.order.setBackgroundResource(R.drawable.cart_disable);
} else {
childname.order.setBackgroundResource(R.drawable.cart_button);
}
childname.order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (status.equals("0")) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(parentActivity);
SharedPreferences customerid = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String opentimes = customerid.getString("open", "");
alertDialogBuilder.setMessage(opentimes);
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
alertDialogBuilder.setCancelable(true);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
String poundre = childname.item_price.getText().toString();
subtmsub = childname.item_name.getText().toString();
subitempri = poundre.replace("£", "");
addcart();
}
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private void addcart() {
loginPreferences = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
SharedPreferences customerid = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPreferences.edit();
String customid = customerid.getString("customerid", "");
String cartdetails = itembasename + " " + subtmsub;
String cartspacong = cartdetails.replace(" ", "$");
cartspacong = cartspacong.replace("&", "and");
String addcarturl = Constant.commonurltake + "cart_process.php?userid=" + customid + "&Item=" + cartspacong + "&Itemcount=1&price=" + subitempri + "&page=items";
Log.d("Cart", addcarturl);
JsonArrayRequest cartreq = new JsonArrayRequest(Request.Method.POST, addcarturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject cartobj = response.getJSONObject(i);
String cartnumber = cartobj.getString("count");
loginPrefsEditor.putString("Count", cartnumber);
BaseActivity.cartnumber.setVisibility(View.VISIBLE);
BaseActivity.cartnumber.setText(cartnumber);
loginPrefsEditor.apply();
if (cartobj.has("message")) {
Toast carttost = Toast.makeText(subcontext, cartobj.getString("message"), Toast.LENGTH_SHORT);
carttost.setGravity(Gravity.CENTER, 0, 0);
carttost.show();
} else {
Toast carttost = Toast.makeText(subcontext, "Product Added To Cart", Toast.LENGTH_SHORT);
carttost.setGravity(Gravity.CENTER, 0, 0);
carttost.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(subcontext, "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
}
According to official documentation
It is not guaranteed that the convertView will have been previously created by getChildView(int, int, boolean, View, ViewGroup)
I think in this case you need to check
if (convertView != null && convertView.getTag() instance of Childnames) {
// reuse the convertView
else
// create new view
}
That is because you are mixing the View types, I think is probably from here:
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return true;
}
You should probably use unique ids for your children because this way they can be mixed up with the group ids.

Tabs refresh when baseadapter button is clicked

i am new to the concept of the fragments i am using the tab layout where one of the tab consists of the list view in that i had used the base adapter to describe the list row where i want to refresh the second tab when button from the first tab is clicked.i had tried the fragment transaction method but its not doing the work that i want please help here
this is the baseadapter
public class Second_adapter extends BaseAdapter {
Context context;
Activity activity;
TextView basename, SubItemprice, itemdesc, SubItemdesc;
LayoutInflater inflater;
ImageView order;
private List<JSONParser> items;
String itembasename, itemde, subtmsub, subitempri;
SharedPreferences.Editor loginPrefsEditor;
public Second_adapter(Context context, List<JSONParser> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.item_clicked, viewGroup, false);
basename = (TextView) view.findViewById(R.id.basename);
SubItemprice = (TextView) view.findViewById(R.id.SubItemprice);
itemdesc = (TextView) view.findViewById(R.id.itemdesc);
SubItemdesc = (TextView) view.findViewById(R.id.SubItemdesc);
order = (ImageView) view.findViewById(R.id.order);
final JSONParser setdata = items.get(i);
basename.setText(setdata.getBaseName());
itemdesc.setText(setdata.getItemdesc());
SubItemdesc.setText(setdata.getSubItemdesc());
SubItemprice.setText(setdata.getSubItemprice());
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itembasename = setdata.getBaseName();
itemde = setdata.getItemdesc();
subtmsub = setdata.getSubItemdesc();
subitempri = setdata.getSubItemprice();
Session userloggedin = new Session(context);
if (userloggedin.isLoggedIn()) {
addcart();
Cart cart = new Cart();
FragmentManager fragmentManager = activity.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.cartfragment, cart);
Toast.makeText(context, "LoggedIn"+ itembasename+itemde+subtmsub+subitempri, Toast.LENGTH_SHORT).show( );
}else{
Toast.makeText(context,"Please Login", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void addcart() {
SharedPreferences customerid=context.getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String addcarturl = "http://standardtakeaway.co.uk/json/cart_ p rocess.p h p?userid = "+customid+" & Item=" + itembasename+itemde+subtmsub+" & Itemcount=1&price="+subitempri;
Log.d("Cart",addcarturl);
JsonArrayRequest cartreq=new JsonArrayRequest(Request.Method.POST, addcarturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0; i<response.length();i++){
try {
JSONObject cartobj=response.getJSONObject(i);
// String count=cartobj.getString("count");
// loginPrefsEditor.putString("Badge",count);
// loginPrefsEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,""+error, Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(cartreq);
}
}
This is the Another tab where i want it to refresh
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View cartfrag = inflater.inflate(R.layout.cart, container, false);
subtotal = (TextView) cartfrag.findViewById(R.id.subtotal);
cartview = (ListView) cartfrag.findViewById(R.id.cartview);
cartitems = new ArrayList<JSONParser>();
cartAdapter = new CartAdapter(getActivity(), cartitems);
cartview.setAdapter(cartAdapter);
check_out = (Button) cartfrag.findViewById(R.id.check_out);
check_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart_check = new Intent(getActivity(), Check.class);
startActivity(cart_check);
}
});
cartdata();
return cartfrag;
}
void cartdata() {
SharedPreferences customerid=getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String carturl = "http://standardtakeaway.co.uk/json/view_cart.php?userid=" + customid;
Log.d("CartData", carturl);
JsonObjectRequest cartreq = new JsonObjectRequest(Request.Method.GET, carturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
}
JSONObject subobj=response.getJSONObject("details");
String subtext=subobj.getString("subtotal");
subtotal.setText(subtext);
} catch (JSONException e) {
e.printStackTrace();
}
cartAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
public static Cart getInstance(String message) {
Cart cart = new Cart();
Bundle bundle = new Bundle();
bundle.putString("MSG", message);
cart.setArguments(bundle);
return cart;
}
}

How to fetch the value from custom ExpandableList Adapter class and set into previous fragment of UI component

I have the following two class one is fragment class and another one is custom expandablelistadapter class. i want the values fetch from the expandablelistadapter class and set the values into fragment UI component like set into textview i describe as comment in following class where to taken values
and where to set the values
SlideContentFragment.java
public class SlidingContentFragment extends Fragment {
static final String LOG_TAG = "SlidingContentFragment";
// store category list from Conastant list, used for to display pagetitle
List<String> catList = AppConstants.CATEGORY_LIST;
private static String[] tmpId = {"35","36","41","42","43","44","45","46"};
ExpandableListView exListCategory;
private SlidingTabLayout mSlidingTabLayout;
/**
* A {#link android.support.v4.view.ViewPager} which will be used in conjunction with the {#link SlidingTabLayout} above.
*/
private ViewPager mViewPager;
//private ExpandableListAdapter mAdapter; // added new
private SamplePagerAdapter myAdapter;
public SlidingContentFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_sliding_content, container, false);
ImageButton cartImgBtn = (ImageButton)v.findViewById(R.id.imgBtnCart);
TextView totalCntItem = (TextView)v.findViewById(R.id.tvCartItemCount);
// I want here set the value of totalCounter from ExpandableList Adapter class when i click on plus
// OR minus button of particular item it updates its value as total count of all item selected
// here following line of code which not worked
totalCntItem.setText(String.format("%d",CategoryItemListAdapter.getTotalCounter()));
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// BEGIN_INCLUDE (setup_viewpager)
// Get the ViewPager and set it's PagerAdapter so that it can display items
this.myAdapter = new SamplePagerAdapter(); // added new
mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(this.myAdapter);
// END_INCLUDE (setup_viewpager)
// BEGIN_INCLUDE (setup_slidingtablayout)
// Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
// it's PagerAdapter set.
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
}
public class SamplePagerAdapter extends PagerAdapter {
public SamplePagerAdapter() {
super();
}
#Override
public int getCount() {
return catList.size();
}
#Override
public boolean isViewFromObject(View view, Object o){
return o == view;
}
#Override
public CharSequence getPageTitle(int position) {
return catList.get(position);
}
#Override
public int getItemPosition (Object object)
{
return PagerAdapter.POSITION_NONE;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
//return super.instantiateItem(container, position);
ViewPager viewPager = (ViewPager)container;
View view = getActivity().getLayoutInflater().inflate(R.layout.pager_item,
container, false);
viewPager.addView(view);
exListCategory = (ExpandableListView)view.findViewById(R.id.myExpandableListView);
//exListCategory.setIndicatorBounds(10,20);
exListCategory.setDividerHeight(2);
if(ConnectionDetector.isInternetAvailable(getActivity())) {
new CategoryJSONAsyncTask().execute("http://..../api/Main/GetCateenOrderCategoryItemListDetail?CategoryID=" + tmpId[position].trim());
}else{
Utility.buildDialog(getActivity()).show();
}
Log.i(String.format("%s: POSITION", LOG_TAG), String.valueOf(position));
Log.i(String.format("%s: CATLIST", LOG_TAG),String.valueOf(catList.get(position)));
view.setTag(position);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
//viewpager
ViewPager viewPager = (ViewPager)container;
View view = (View) object;
view.getTag(position);
viewPager.removeView(view);
//((ViewPager) container).removeView((View) object);
}
}
public class CategoryJSONAsyncTask extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
HttpGet httppost = new HttpGet(params[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
return result;
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ArrayList<CategoryParentItemList> listParent = fetchResponse(result.replace("\n","").trim());
/*for (Object obj : listParent){
if(obj.getClass() == CategoryParentItemList.class){
CategoryParentItemList p = (CategoryParentItemList)obj;
System.out.println("P-ItemName: "+ p.subCategoryName);
}
}*/
CategoryItemListAdapter adapter = new CategoryItemListAdapter(SlidingContentFragment.this.getActivity(), listParent);
exListCategory.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
public ArrayList<CategoryParentItemList> fetchResponse(String result)
{
ArrayList<CategoryParentItemList> listParent = new ArrayList<>();
if (!result.equals(""))
{
try
{
JSONObject jsono = new JSONObject(result);
JSONArray jarray = jsono.getJSONArray("SBL");
CategoryParentItemList parent;
for (int i = 0; i < jarray.length(); i++)
{
ArrayList<CategoryChildListItem> childrens = new ArrayList<>();
childrens.clear();
CategoryChildListItem child;
JSONObject object = jarray.getJSONObject(i);
//System.out.println("SCI: " + object.getInt("SubCategoryID"));
//System.out.println("SCN: " + object.getString("SubCategoryName"));
JSONArray subItemArray = object.getJSONArray("SubCategoryItemList");
if (subItemArray.length() > 0)
{
for (int j = 0; j < subItemArray.length(); j++)
{
JSONObject subItemObject = subItemArray.getJSONObject(j);
String strItemName = subItemObject.getString("ItemName");
String strDefaultPrice = subItemObject.getString("DefaultPrice");
child = new CategoryChildListItem(strItemName, strDefaultPrice);
childrens.add(child);
//Log.i("strItemName", strItemName);
//Log.i("strDefaultPrice", strDefaultPrice);
}
parent = new CategoryParentItemList(object.getString("SubCategoryName"),childrens);
listParent.add(parent);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
return listParent;
}
}
CategoryListItemAdaptor.java
public class CategoryItemListAdapter extends BaseExpandableListAdapter{
private Context context;
public static int totalCounter=0;
private ArrayList<CategoryParentItemList> listParent;
static class ViewHolderGroup {
public TextView lblSubCategoryName;
}
static class ViewHolderChild {
public TextView lblItemName;
public TextView lblDefualtPrice;
public TextView lblQty;
public ImageButton imgPlus;
public ImageButton imgMinus;
}
public CategoryItemListAdapter(Context context, ArrayList<CategoryParentItemList> listParent) {
super();
this.context = context;
this.listParent = listParent;
}
#Override
public int getGroupCount() {
return listParent.size();
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<CategoryChildListItem> ch = listParent.get(groupPosition).getChildList();
return ch.size();
}
#Override
public Object getGroup(int groupPosition) {
return listParent.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<CategoryChildListItem> ch = listParent.get(groupPosition).getChildList();
return ch.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
//CategoryParentItemList parentItem = (CategoryParentItemList)listParent.get(groupPosition);
CategoryParentItemList parentItem = (CategoryParentItemList) getGroup(groupPosition);
ViewHolderGroup holderGroup;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.group_header, null);
holderGroup = new ViewHolderGroup();
holderGroup.lblSubCategoryName = (TextView) convertView.findViewById(R.id.tvItemName);
convertView.setTag(holderGroup);
} else {
holderGroup = (ViewHolderGroup) convertView.getTag();
}
holderGroup.lblSubCategoryName.setText(parentItem.getSubCategoryName());
return convertView;
}
#Override
public View getChildView(int groupPosition,int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
//final CategoryParentItemList parentItem = (CategoryParentItemList) listParent.get(groupPosition);
//final CategoryChildListItem childItem = (CategoryChildListItem) parentItem.getChildList().get(childPosition);
CategoryChildListItem childItem = (CategoryChildListItem) getChild(groupPosition, childPosition);
ViewHolderChild holder;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_row, null);
holder = new ViewHolderChild();
holder.lblItemName = (TextView) convertView.findViewById(R.id.tvSubItemName);
holder.lblDefualtPrice = (TextView) convertView.findViewById(R.id.tvrRupees);
holder.lblQty = (TextView) convertView.findViewById(R.id.tvQty);
holder.imgPlus = (ImageButton) convertView.findViewById(R.id.imageButtonPlus);
holder.imgMinus = (ImageButton) convertView.findViewById(R.id.imageButtonMinus);
convertView.setTag(holder);
} else {
holder = (ViewHolderChild) convertView.getTag();
}
holder.lblItemName.setText(childItem.getSubItemName());
holder.lblDefualtPrice.setText(childItem.getDefaultPrice());
int tmpCount = Integer.parseInt(holder.lblQty.getText().toString());
holder.imgPlus.setOnClickListener(new ClickUpdateListener(childItem,holder, tmpCount));
holder.imgMinus.setOnClickListener(new ClickUpdateListener(childItem,holder, tmpCount));
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
public static int getTotalCounter() {
return totalCounter;
}
private class ClickUpdateListener implements View.OnClickListener {
ViewHolderChild holder;
public CategoryChildListItem childItem;
int counter = 0;
String counterMin;
public ClickUpdateListener(CategoryChildListItem childItem,ViewHolderChild holder, int cnt) {
this.childItem = childItem;
this.holder = holder;
this.counter = cnt;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.imageButtonPlus) {
counter = counter + 1;
totalCounter+=1;
System.out.println(childItem.getSubItemName()+" : "+childItem.getDefaultPrice() + ": C+ :" + counter);
holder.lblQty.setText(String.format("%d", counter));
notifyDataSetChanged();
}
if(v.getId() == R.id.imageButtonMinus){
counterMin = (String) holder.lblQty.getText();
counter = Integer.parseInt(counterMin.toString().trim());
counterMin = null;
if(counter > 0) {
counter = counter - 1;
totalCounter-=1;
System.out.println(childItem.getSubItemName()+" : "+childItem.getDefaultPrice() + ": C- :" + counter);
holder.lblQty.setText(String.format("%d", counter));
notifyDataSetChanged();
}else{
Toast.makeText(context,"Qty Zero",Toast.LENGTH_SHORT).show();
}
}
}
}
}

Categories