I have this fragment class that is showed when an element is selected in a navigation drawer:
public class RecibidosFragment extends Fragment {
public ExpandListAdapterMensaje ExpAdapter;
public ArrayList<ChildMensaje> ListChild=null;
public ArrayList<Mensaje> ListMensajes=null;
public ExpandableListView ExpandList;
public ProgressDialog dialog;
public ArrayList<ArrayList<ChildMensaje>> ListChildXXXXXXXXX = null;
TextView tv;
Context mContext;
/**
* Returns a new instance of this fragment for the given section number.
*/
public static RecibidosFragment newInstance() {
RecibidosFragment fragment = new RecibidosFragment();
return fragment;
}
public RecibidosFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_recibidos, container,
false);
mContext = container.getContext();
tv = (TextView)rootView.findViewById(R.id.textView);
tv.setText(cargartodo());
ExpandList=(ExpandableListView)rootView.findViewById(R.id.expandableListView2);
ListMensajes = new ArrayList<Mensaje>();
ListChild = new ArrayList<ChildMensaje>();
ListChildXXXXXXXXX = new ArrayList<ArrayList<ChildMensaje>>();
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((menu_mensajes) activity).onSectionAttached(1);
}
public String cargartodo(){
String arreglo = loadJSONFromFile();
arreglo = "[" + arreglo+ "]";
Mensaje men =null;
ChildMensaje chmen=null;
try {
ArrayList<Mensaje> list = new ArrayList<Mensaje>();
ArrayList<ChildMensaje> ch_list;
JSONArray jsonArray = new JSONArray(arreglo);
JSONObject jsonObject2 = jsonArray.getJSONObject(0);
if(jsonObject2.optString("success").equals("0")){
arreglo="No tiene mensajes recibidos.";
}else {
for (int i = 0; i < jsonArray.length(); i++) {
arreglo="inside5";
JSONObject jsonObject = jsonArray.getJSONObject(i);
men = new Mensaje(jsonObject.optString("asunto"), jsonObject.optString("origen"), jsonObject.optString("fecha"));
ListMensajes.add(men);
chmen = new ChildMensaje(jsonObject.optString("mensaje"));
ListChild.add(chmen);
ListChildXXXXXXXXX.add(ListChild);
ExpAdapter = new ExpandListAdapterMensaje(mContext, ListMensajes, ListChildXXXXXXXXX);
ExpandList.setAdapter(ExpAdapter);
}}
} catch (JSONException e) {
e.printStackTrace();
}
return arreglo;
}
public String loadJSONFromFile() {
String json = null;
try {
//
FileInputStream is = mContext.openFileInput("mensajes.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
With :
public class ChildMensaje {
public String mensaje;
public ChildMensaje(){}
public ChildMensaje(String mensaje){
this.mensaje=mensaje;
}
public String getMensaje() {
return mensaje;
}
public void setMensaje(String mensaje) {
this.mensaje = mensaje;
}
}
public class ExpandListAdapterMensaje extends BaseExpandableListAdapter {
public Context context;
public ArrayList<Mensaje> noticiasArrayList;
public ArrayList<ArrayList<ChildMensaje>> ListChild;
public ExpandListAdapterMensaje(Context context, ArrayList<Mensaje> noticiasArrayList,ArrayList<ArrayList<ChildMensaje>> ListChild) {
this.context = context;
this.noticiasArrayList = noticiasArrayList;
this.ListChild=ListChild;
}
#Override
public ChildMensaje getChild(int groupPosition, int childPosition) {
return ListChild.get(groupPosition).get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ChildMensaje child = getChild(groupPosition, childPosition);
ViewHolder holder=null;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_row, null);
holder=new ViewHolder();
holder.mensaje=(TextView)convertView.findViewById(R.id.mensaje);
convertView.setTag(holder);
}
else {
holder=(ViewHolder)convertView.getTag();
}
holder.mensaje.setText(child.getMensaje());
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return ListChild.get(groupPosition).size();
}
#Override
public Mensaje getGroup(int groupPosition) {
return noticiasArrayList.get(groupPosition);
}
#Override
public int getGroupCount() {
return noticiasArrayList.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
Mensaje not = (Mensaje) getGroup(groupPosition);
ViewHolder holder= null;
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.list_row, null);
holder=new ViewHolder();
holder.asunto=(TextView)convertView.findViewById(R.id.titulo);
holder.fecha=(TextView)convertView.findViewById(R.id.fecha);
holder.origen=(TextView)convertView.findViewById(R.id.dirigido);
convertView.setTag(holder);
}
else{
holder=(ViewHolder)convertView.getTag();
}
holder.asunto.setText(not.getAsunto());
holder.fecha.setText(not.getFecha());
holder.origen.setText(not.getOrigen());
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean areAllItemsEnabled()
{
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
static class ViewHolder{
TextView asunto, fecha,origen, mensaje;
}
}
public class Mensaje {
public String origen;
public String asunto;
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getOrigen() {
return origen;
}
public void setOrigen(String origen) {
this.origen = origen;
}
String fecha;
ArrayList<ChildMensaje> Items;
public Mensaje() {
}
public Mensaje(String asunto, String origen, String fecha) {
this.asunto = asunto;
this.fecha = fecha;
this.origen = origen;
}
public String getAsunto() {
return asunto;
}
public void setAsunto(String asunto) {
this.asunto = asunto;
}
public ArrayList<ChildMensaje> getItems() {
return Items;
}
public void setItems(ArrayList<ChildMensaje> Items) {
this.Items = Items;
}
}
My issue just appear when I'm running the app. Just in the moment that I clicked the button for go to this fragment a message appear, The aplication must to be stopped and crashed. I was just commenting the code line per line and I just know that the code is executed until that line ->
ListMensajes.add(men);
So, what I'm doing wrong ?? It has some solution ??
Thanks ;)
Ray's comment is right. It seems that the error occurs in your onCreateView() method.
tv.setText(cargartodo());
...
ListMensajes = new ArrayList<Mensaje>();
cargartodo() was called before the ListMensajes was initialized. In the cargartodo() method, ListMensajes.add() will throw a NullPointerException.
Change public ArrayList<Mensaje> ListMensajes=null to public ArrayList<Mensaje> ListMensajes= new ArrayList<Mensaje> , it may work.
Related
I am getting data from the SQL database to the android Expandable listview.
All of my data is correct except the listview group is repeated the same amount of the listview children.
I have no idea why and I have tried everything that came into my mind.
Anyways I am using 2 queries!
one to get the group and one to get the group children!
Here is my code: AsyncTask:
private class SyncData extends AsyncTask<String, String, String> {
String msg;
#Override
protected void onPreExecute() //Starts the progress dailog
{
System.out.println("Start");
//lottieAnimationView.playAnimation();
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
String query = "SELECT SalesInvoice.SalesInvoiceID,SalesInvoice.SalesInvoiceSerial,SalesInvoice.SalesInvoiceDate,SalesInvoice.SalesInvoiceItemCount,SalesInvoice.SalesInvoiceTotal,SalesInvoice.SalesInvoiceTaxs,SalesInvoice.SalesInvoiceLastTotal,SalesInvoice.SalesInvoiceBranchID FROM SalesInvoice where SalesInvoiceID = '321' AND SalesInvoiceBranchID = '2'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
ClassListItems classListItems = new ClassListItems(rs.getString("SalesInvoiceSerial"),rs.getString("SalesInvoiceDate"),rs.getString("SalesInvoiceItemCount"),rs.getString("salesInvoiceTotal"),rs.getString("SalesInvoiceTaxs"),rs.getString("SalesInvoiceLastTotal"));
String query2 = "SELECT SalesProductName FROM SalesInvoiceDetail WHERE SalesInvoiceID = '"+rs.getString("SalesInvoiceID")+"'";
Statement stmt2 = conn.createStatement();
ResultSet rs2 = stmt2.executeQuery(query2);
if (rs2 != null){
while (rs2.next()){
System.out.println("ssss");
classListItems.getChildItemList().add(new ChildItem(rs2.getString("SalesProductName")));
itemArrayList.add(classListItems);
}
msg = "Found";
success = true;
}else {
msg = "Not Found";
success = false;
}
//Picasso.with(agzakhana_mainAr.this).load(rs.getString("SpecialityIcon")).into(specialityicon);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
//progress2.hideProgress();
progressDialog.hide();
if (msg!=null){
Toast.makeText(MainActivity.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
System.out.println("EndNotSuccess");
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, MainActivity.this);
exlistView21.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
exlistView21.setAdapter(myAppAdapter);
System.out.println("End");
} catch (Exception ex) {
}
}
}
}
Adapter:
public class MyAppAdapter extends BaseExpandableListAdapter//has a class viewholder which holds
{
public class ViewHolder {
TextView invoicenum;
TextView date;
TextView itemscount;
TextView total;
TextView tax;
TextView lasttotal;
TextView textchild;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(parkingList);
System.out.println("called");
}
#Override
public int getGroupCount() {
return parkingList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return parkingList.get(groupPosition).getChildItemList().size();
}
#Override
public Object getGroup(int groupPosition) {
return null;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return parkingList.get(groupPosition).getChildItemList().get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#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) {
View rowView = convertView;
MyAppAdapter.ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.list_items, parent, false);
viewHolder = new MyAppAdapter.ViewHolder();
//initialize our labels
viewHolder.invoicenum = (TextView) rowView.findViewById(R.id.invoicenum);
viewHolder.date = (TextView) rowView.findViewById(R.id.date);
viewHolder.itemscount = (TextView) rowView.findViewById(R.id.itemcount);
viewHolder.total = (TextView) rowView.findViewById(R.id.total);
viewHolder.tax = (TextView) rowView.findViewById(R.id.tax);
viewHolder.lasttotal = (TextView) rowView.findViewById(R.id.lasttotal);
rowView.setTag(viewHolder);
} else {
viewHolder = (MyAppAdapter.ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.invoicenum.setText(parkingList.get(groupPosition).getSalesInvoiceSerial());
viewHolder.itemscount.setText(parkingList.get(groupPosition).getSalesInvoiceItemCount());
viewHolder.date.setText(parkingList.get(groupPosition).getSalesInvoiceDate());
viewHolder.total.setText(parkingList.get(groupPosition).getSalesInvoiceTotal());
viewHolder.lasttotal.setText(parkingList.get(groupPosition).getSalesInvoiceLastTotal());
viewHolder.tax.setText(parkingList.get(groupPosition).getSalesInvoiceTax());
System.out.println("PARENT IS: "+parkingList.get(groupPosition).getSalesInvoiceSerial());
// Picasso.with(context).load(parkingList.get(position).getDiscountimage()).into(viewHolder.imagediscount);
exlistView21.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
}
});
return rowView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View resultView = convertView;
ViewHolder holder;
LayoutInflater inflater = getLayoutInflater();
if (resultView == null) {
resultView = inflater.inflate(R.layout.listchildren, null); //TODO change layout id
holder = new ViewHolder();
holder.textchild = (TextView) resultView.findViewById(R.id.child); //TODO change view id
resultView.setTag(holder);
} else {
holder = (ViewHolder) resultView.getTag();
}
System.out.println("CHILD IS: "+parkingList.get(childPosition).getChildItemList().get(childPosition).getSs());
holder.textchild.setText(parkingList.get(childPosition).getChildItemList().get(childPosition).getSs());
return resultView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
// public void filter(String charText) {
// charText = charText.toLowerCase(Locale.getDefault());
// itemArrayList.clear();
// if (charText.length() == 0) {
// itemArrayList.addAll(arraylist);
//
// } else {
// for (ClassListItems2 st : arraylist) {
// if (st.getSpecialityname().toLowerCase(Locale.getDefault()).contains(charText)) {
// itemArrayList.add(st);
// }
//
// }
// }
// notifyDataSetChanged();
// }
}
}
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.
When I click on the child views on my app it does not respond to the click. I pretty much googled this as much as I could without any success. I tried debugging it and when I touch the child it does not go in the onclick method
Activity class
public class LetestNews extends ExpandableListActivity{
private ArrayList<String> parentItems = new ArrayList<String>();
private ArrayList<Object> childItems = new ArrayList<Object>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this is not really necessary as ExpandableListActivity contains an ExpandableList
//setContentView(R.layout.main);
ExpandableListView expandableList = getExpandableListView(); // you can use (ExpandableListView) findViewById(R.id.list)
expandableList.setDividerHeight(2);
expandableList.setGroupIndicator(null);
expandableList.setClickable(true);
setGroupParents();
setChildData();
ExpandableAdapter adapter = new ExpandableAdapter(parentItems, childItems);
adapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
expandableList.setAdapter(adapter);
//expandableList.setOnChildClickListener(this);
expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id) {
/* You must make use of the View v, find the view by id and extract the text as below*/
Toast.makeText(getBaseContext(), "Shaan is a monkey",
Toast.LENGTH_SHORT).show();
return true; // i missed this
}
});
}
public void setGroupParents() {
try {
FileInputStream newsIn = openFileInput("news.txt");
String newsObj = "";
String objEnc="";
Gson gson=new Gson();
BufferedReader inputNews = new BufferedReader(new InputStreamReader(newsIn, "UTF-8"));
StringBuilder sbuilderNews = new StringBuilder();
newsObj = inputNews.readLine();
while (newsObj != null) {
sbuilderNews.append(newsObj);
newsObj = inputNews.readLine();
if (newsObj != null) {
// sbuilder.append("\n");
}
}
newsIn.close();
newsObj = sbuilderNews.toString();
SubredditNews objNews = gson.fromJson(newsObj, SubredditNews.class);
ArrayList<SubredditIN>subredditObjects=objNews.subreddits;
for(int i=0;i<subredditObjects.size();i++){
parentItems.add(subredditObjects.get(i).name);
}
}catch(Exception e){
}
}
public void setChildData() {
// Android
ArrayList<String> child = new ArrayList<String>();
String a="";
/*child.add("Core");
child.add("Games");
childItems.add(child);*/
try {
FileInputStream newsIn = openFileInput("news.txt");
String newsObj = "";
String objEnc="";
Gson gson=new Gson();
BufferedReader inputNews = new BufferedReader(new InputStreamReader(newsIn, "UTF-8"));
StringBuilder sbuilderNews = new StringBuilder();
newsObj = inputNews.readLine();
while (newsObj != null) {
sbuilderNews.append(newsObj);
newsObj = inputNews.readLine();
if (newsObj != null) {
// sbuilder.append("\n");
}
}
newsIn.close();
newsObj = sbuilderNews.toString();
SubredditNews objNews = gson.fromJson(newsObj, SubredditNews.class);
ArrayList<SubredditIN>subredditObjects=objNews.subreddits;
for(int i=0;i<objNews.subreddits.size();i++){
child = new ArrayList<String>();
for(int j=0;j<objNews.subreddits.get(i).posts.size();j++) {
subredditObjects.get(i).setURL();
a=subredditObjects.get(i).getPostLink();
child.add(objNews.subreddits.get(i).posts.get(j));
Log.i("this is the link", a);
}
childItems.add(child);
}
}catch(Exception e){
String dd="";
}
}
}
Adapter class
public class ExpandableAdapter extends BaseExpandableListAdapter {
private Activity activity;
private ArrayList<Object> childtems;
private LayoutInflater inflater;
private ArrayList<String> parentItems, child;
public ExpandableAdapter(ArrayList<String> parents, ArrayList<Object> childern) {
this.parentItems = parents;
this.childtems = childern;
}
public void setInflater(LayoutInflater inflater, Activity activity) {
this.inflater = inflater;
this.activity = activity;
}
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
child = (ArrayList<String>) childtems.get(groupPosition);
TextView textView = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.group, null);
}
textView = (TextView) convertView.findViewById(R.id.textView1);
textView.setText(child.get(childPosition));
//textView.setText(Html.fromHtml("<a href=http://www.stackoverflow.com> STACK OVERFLOW "));
// textView.setMovementMethod(LinkMovementMethod.getInstance());
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(activity, child.get(childPosition),
Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.child, null);
}
((CheckedTextView) convertView).setText(parentItems.get(groupPosition));
((CheckedTextView) convertView).setChecked(isExpanded);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public int getChildrenCount(int groupPosition) {
return ((ArrayList<String>) childtems.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return null;
}
#Override
public int getGroupCount() {
return parentItems.size();
}
#Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
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();
}
}
}
}
}
Hi need to prepare screen like this
Here is my code of expandable list view
Adapter class: NewAdapter.java
public class NewAdapter extends BaseExpandableListAdapter {
public ArrayList<ParentBean> groupItem;
ArrayList<String> tempChild;
public ArrayList<Object> Childtem = new ArrayList<Object>();
public LayoutInflater minflater;
public Activity activity;
public NewAdapter(ArrayList<ParentBean> grList, ArrayList<Object> childItem) {
groupItem = grList;
this.Childtem = childItem;
}
public void setInflater(LayoutInflater mInflater, Activity act) {
this.minflater = mInflater;
activity = act;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
tempChild = (ArrayList<String>) Childtem.get(groupPosition);
TextView text = null;
if (convertView == null) {
convertView = minflater.inflate(R.layout.childrow, null);
}
text = (TextView) convertView.findViewById(R.id.textView1);
text.setText(tempChild.get(0));
text = (TextView) convertView.findViewById(R.id.textView2);
text.setText(tempChild.get(1));
text = (TextView) convertView.findViewById(R.id.textView3);
text.setText(tempChild.get(2));
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, tempChild.get(childPosition),
Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return 1;
}
#Override
public Object getGroup(int groupPosition) {
return null;
}
#Override
public int getGroupCount() {
return groupItem.size();
}
#Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
ViewHolder holder=null;
if (convertView == null) {
convertView = minflater.inflate(R.layout.grouprow, null);
holder = new ViewHolder();
holder.name=(TextView)convertView.findViewById(R.id.playername);
holder.team = (TextView) convertView.findViewById(R.id.vs);
holder.salary = (TextView) convertView.findViewById(R.id.salary);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ParentBean playerdetails = groupItem.get(groupPosition);
holder.name.setText(playerdetails.getPlayername());
holder.team.setText(playerdetails.getPlayerteam());
holder.salary.setText(playerdetails.getPlayersalary());
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
private class ViewHolder {
TextView team;
TextView name;
TextView salary;
}
class ParentBean{
String playername,playerteam,playersalary;
public ParentBean(String playername,String playerteam,String playersalary) {
this.playername=playername;
this.playersalary=playersalary;
this.playerteam=playerteam;
}
/**
* #return the playername
*/
public String getPlayername() {
return playername;
}
/**
* #param playername the playername to set
*/
public void setPlayername(String playername) {
this.playername = playername;
}
/**
* #return the playerteam
*/
public String getPlayerteam() {
return playerteam;
}
/**
* #param playerteam the playerteam to set
*/
public void setPlayerteam(String playerteam) {
this.playerteam = playerteam;
}
/**
* #return the playersalary
*/
public String getPlayersalary() {
return playersalary;
}
/**
* #param playersalary the playersalary to set
*/
public void setPlayersalary(String playersalary) {
this.playersalary = playersalary;
}
}
}
Here is my activity : MainActivity.java
public class MainActivity extends ExpandableListActivity implements
OnChildClickListener {
Context context;
ArrayList<ParentBean> groupItem = new ArrayList<ParentBean>();
ArrayList<Object> childItem = new ArrayList<Object>();
NewAdapter mNewAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ExpandableListView expandbleLis = getExpandableListView();
expandbleLis.setDividerHeight(2);
expandbleLis.setGroupIndicator(null);
expandbleLis.setClickable(true);
expandbleLis.setFocusable(true);
context=this;
getData();
mNewAdapter = new NewAdapter(groupItem, childItem);
mNewAdapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE),this);
getExpandableListView().setAdapter(mNewAdapter);
expandbleLis.setOnChildClickListener(this);
}
public void getData() {
JsonDataCallback callback=new JsonDataCallback(MainActivity.this) {
#Override
public void receiveData(Object object) {
String jsonData=(String)object;
setData(jsonData);
}
};
callback.execute("http://111.93.7.119:8080/FirstPickService/Players?sportid=fc2e88e6-ac87-4d27-b6b3-863baa9f06ec",null,null);
}
protected void setData(String jsonData) {
try {
JSONObject players=new JSONObject(jsonData);
final JSONArray playersArray=players.getJSONArray("players");
for(int i=0;i<playersArray.length();i++)
{
JSONObject jsonObj=playersArray.getJSONObject(i);
String teamplayer=jsonObj.getString("playerfullname");
String psalary=jsonObj.getString("playerprice");
String strTeamVS=jsonObj.getString("teamid")+"#"+jsonObj.getString("awayteam");
groupItem.add(mNewAdapter.new ParentBean(teamplayer, psalary, strTeamVS));
String strsalary = jsonObj.getString("playerpricelong");
ArrayList<String> child = new ArrayList<String>();
child.add(psalary);
child.add(strTeamVS);
child.add(strsalary);
childItem.add(child);
}
mNewAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(MainActivity.this, "Clicked On Child",
Toast.LENGTH_SHORT).show();
return true;
}
}
I am not sure but I have used a button for select, because of that expandable list losing focus and is not showing childrow when click on the listitem...
Try making the select button non-focusable in the xml.