My data from sql database to android listview is repeated - java

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

Related

Sql query in Java Android

I have lots of questions that I didn't find answers to.
First of all, I have two tables in MS Sql server, one is called country that contains country id and country name, and one is called family which contains country id, family id, family name and family info. The problem I am facing is how can I write a query in Java Android that gets the id of the country and compare it with the id of the country in the families table and then for each country there is its own family.
I have tried inner joins but couldn't know how to do it.
Here is my code so far:
public class InsideCountries extends AppCompatActivity {
private ArrayList<ClassListItems> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
private ListView listView;
private TextView ttl;// Listview
private boolean success = false; // boolean
private ConnectionClass connectionClass; //Connection Class Variable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inside_countries);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
ttl = (TextView) findViewById(R.id.title) ;
ttl.setText(getIntent().getStringExtra("CountriesName"));
listView = (ListView) findViewById(R.id.listvieww); //Listview Declaration
connectionClass = new ConnectionClass(); // Connection Class Initialization
itemArrayList = new ArrayList<ClassListItems>(); // Arraylist Initialization
// Calling Async Task
SyncData orderData = new SyncData();
orderData.execute("");
}
// Async Task has three overrided methods,
private class SyncData extends AsyncTask<String, String, String> {
String msg = "No Data Found";
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(InsideCountries.this, "Synchronising",
"Please Wait...", true);
}
#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) {
msg = "Please Check Your Connection";
success = false;
} else {
// Change below query according to your own database.
String query = "query here";
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 {
itemArrayList.add(new ClassListItems(rs.getString("name")));
} 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) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
Toast.makeText(InsideCountries.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, InsideCountries.this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends BaseAdapter //has a class viewholder which holds
{
public class ViewHolder
{
TextView textName;
}
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);
}
#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, View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder= null;
if (rowView == null)
{
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.list_content, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = (TextView) rowView.findViewById(R.id.textName);
rowView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getName()+"");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(InsideCountries.this,Inside_Families.class);
intent.putExtra("Family",parkingList.get(position).getName());
startActivity(intent);
}
});
return rowView;
}
}
}
Any help would be apreciated!?

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

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.

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

Not creating arraylist Object Class from JSON in fragment (Android)

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.

Categories