如何在向其添加新项目时更新Expandable listview

时间:2017-01-15 15:41:19

标签: android listview expandablelistview

我创建了一个可扩展的列表视图,当列表视图到达底部时,它会从sqlite加载数据。它再次使用异步任务从sqlite加载另一组数据。此时,标题将使用新数据进行更新,但最新的子视图数据是空的,任何人都可以告诉我如何在新数据加载时更新/刷新可扩展列表适配器。

适配器:

public class DaybookExpandableAdapter extends BaseExpandableListAdapter {
String updatedate = "";
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<Daybooklist>> _listDataChild;
private DatabaseHandler databaseHandler;
boolean isListScrolling;

public DaybookExpandableAdapter(Context context, List<String> listDataHeader,
                                HashMap<String, List<Daybooklist>> listChildData) {
    this._context = context;
    this._listDataHeader = listDataHeader;
    this._listDataChild = listChildData;
}

@Override
public Object getChild(int groupPosition, int childPosititon) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .get(childPosititon);
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public View getChildView(int groupPosition, final int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {

    /*final String childText = (String) getChild(groupPosition, childPosition);
    final String childtime = (String) getChild(groupPosition,childPosition);*/
    Daybooklist daybooklist = (Daybooklist) getChild(groupPosition, childPosition);
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.model_daybook_listitem, null);
    }

    TextView txtname = (TextView) convertView.findViewById(R.id.tv_daybook_name);
    TextView txttime = (TextView) convertView.findViewById(R.id.tv_daybook_time);
    TextView day_name = (TextView) convertView.findViewById(R.id.tv_daybook_name);
    TextView day_description = (TextView) convertView.findViewById(R.id.tv_daybook_description);
    TextView day_type = (TextView) convertView.findViewById(R.id.tv_daybook_type);
    TextView day_amount = (TextView) convertView.findViewById(R.id.tv_daybook_amount);
    TextView day_usertype = (TextView) convertView.findViewById(R.id.tv_usertype);
    TextView day_time = (TextView) convertView.findViewById(R.id.tv_daybook_time);
    ImageView day_check = (ImageView) convertView.findViewById(R.id.img_doneall);
    TextView daybook_location = (TextView) convertView.findViewById(R.id.tv_daybook_location);


    txtname.setText(daybooklist.getName());
    txttime.setText(daybooklist.getCtime());
    databaseHandler = new DatabaseHandler(_context);
    if (daybooklist.getUsertype() != null && !daybooklist.getUsertype().isEmpty()) {
        if (daybooklist.getUsertype().startsWith("farmer") | daybooklist.getUsertype().startsWith("singleworker") | daybooklist.getUsertype().startsWith("groupworker") | daybooklist.getUsertype().startsWith("payvehicle")) {
            if (daybooklist.getUsertype().startsWith("farmer")) {
                day_name.setText(daybooklist.getName());
                day_description.setText(daybooklist.getDescription());
                String mobno = daybooklist.getMobileno();
                Log.e("mobno", mobno);
                String locat = String.valueOf(databaseHandler.getfarmerlocation(mobno));
                locat = locat.replaceAll("\\[", "").replaceAll("\\]", "");
                Log.e("farmerlocation", locat);
                daybook_location.setText(locat);
                day_type.setText(daybooklist.getType());
                if (daybooklist.getName() != null && daybooklist.getName().startsWith("no")) {
                    day_name.setText(" ");
                } else if (daybooklist.getDescription() != null && daybooklist.getDescription().startsWith("no")) {
                    day_description.setText(" ");
                }

                day_amount.setText("\u20B9" + daybooklist.getExtraamt());
                if (daybooklist.getAmountout().startsWith("0.0") | daybooklist.getAmountout().startsWith("0")) {
                    //     day_amount.setTextColor(activity.getResources().getColor(R.color.green));
                    Log.e("Amountout", daybooklist.getAmountout());
                    day_check.setVisibility(View.INVISIBLE);
                } else {
                    //    day_amount.setTextColor(activity.getResources().getColor(R.color.album_title));
                    Log.e("Amountout", daybooklist.getAmountout());
                    day_check.setVisibility(View.VISIBLE);
                }

                day_time.setText(daybooklist.getCtime());
            } else {
                day_name.setText(daybooklist.getName());
                day_description.setText(daybooklist.getDescription());
                daybook_location.setText(daybooklist.getType());
                day_type.setText(daybooklist.getType());
                if (daybooklist.getName() != null && daybooklist.getName().startsWith("no")) {
                    day_name.setText(" ");
                } else if (daybooklist.getDescription() != null && daybooklist.getDescription().startsWith("no")) {
                    day_description.setText(" ");
                }

                day_amount.setText("\u20B9" + daybooklist.getExtraamt());
                if (daybooklist.getAmountout().startsWith("0.0") | daybooklist.getAmountout().startsWith("0")) {
                    //  day_amount.setTextColor(activity.getResources().getColor(R.color.green));
                    Log.e("Amountout", daybooklist.getAmountout());
                    day_check.setVisibility(View.INVISIBLE);
                } else {
                    //  day_amount.setTextColor(activity.getResources().getColor(R.color.album_title));
                    Log.e("Amountout", daybooklist.getAmountout());
                    day_check.setVisibility(View.VISIBLE);
                }

                day_time.setText(daybooklist.getCtime());
            }


        } else if (daybooklist.getUsertype().startsWith("advancefarmer") | daybooklist.getUsertype().startsWith("workeradvance") | daybooklist.getUsertype().startsWith("kgroupadvance") | daybooklist.getUsertype().startsWith("otherexpense") | daybooklist.getUsertype().startsWith("vehicle")) {
            if (daybooklist.getUsertype().startsWith("advancefarmer")) {
                day_name.setText(daybooklist.getName());
                day_description.setText(daybooklist.getDescription());
                day_type.setText(daybooklist.getType());
                String mobno = daybooklist.getMobileno();
                Log.e("mobno", mobno);
                String locat = String.valueOf(databaseHandler.getfarmerlocation(mobno));
                locat = locat.replaceAll("\\[", "").replaceAll("\\]", "");
                Log.e("farmerlocation", locat);
                daybook_location.setText(locat);
                if (daybooklist.getName() != null && daybooklist.getName().startsWith("no")) {
                    day_name.setText(" ");
                } else if (daybooklist.getDescription() != null && daybooklist.getDescription().startsWith("no")) {
                    day_description.setText(" ");
                }
                Log.e("amountout", daybooklist.getAmountout());
                day_amount.setText("\u20B9" + daybooklist.getAmountout());
                day_time.setText(daybooklist.getCtime());
            } else {
                day_name.setText(daybooklist.getName());
                day_description.setText(daybooklist.getType());
                day_type.setText(daybooklist.getType());
                daybook_location.setText(daybooklist.getDescription());
                if (daybooklist.getName() != null && daybooklist.getName().startsWith("no")) {
                    day_name.setText(" ");
                } else if (daybooklist.getDescription() != null && daybooklist.getDescription().startsWith("no")) {
                    day_description.setText(" ");
                }
                Log.e("amountout", daybooklist.getAmountout());
                day_amount.setText("\u20B9" + daybooklist.getAmountout());
                day_time.setText(daybooklist.getCtime());
            }


        } else if (daybooklist.getUsertype().startsWith("buyer")) {
            day_name.setText(daybooklist.getName());
            day_description.setText(daybooklist.getDescription());
            day_amount.setText("\u20B9" + daybooklist.getAmountin());
            day_type.setText(" ");
            day_time.setText(daybooklist.getCtime());
            daybook_location.setText(daybooklist.getType());
        }
        if (daybooklist.getUsertype().startsWith("farmer")) {
            day_usertype.setText("F");
            day_usertype.setBackgroundResource(R.drawable.textview_farmer);
        } else if (daybooklist.getUsertype().startsWith("advancefarmer")) {
            day_usertype.setText("FA");
            day_usertype.setBackgroundResource(R.drawable.textview_farmer);
        } else if (daybooklist.getUsertype().startsWith("singleworker")) {
            day_usertype.setText("W");
            day_usertype.setBackgroundResource(R.drawable.textview_worker);
        } else if (daybooklist.getUsertype().startsWith("workeradvance")) {
            day_usertype.setText("WA");
            day_usertype.setBackgroundResource(R.drawable.textview_worker);
        } else if (daybooklist.getUsertype().startsWith("groupworker")) {
            day_usertype.setText("G");
            day_usertype.setBackgroundResource(R.drawable.textview_worker);
        } else if (daybooklist.getUsertype().startsWith("kgroupadvance")) {
            day_usertype.setText("GA");
            day_usertype.setBackgroundResource(R.drawable.textview_worker);
        } else if (daybooklist.getUsertype().startsWith("otherexpense")) {
            day_usertype.setText("E");
            day_usertype.setBackgroundResource(R.drawable.textview_otherexpense);
        } else if (daybooklist.getUsertype().startsWith("vehicle")) {
            day_usertype.setText("V");
            day_usertype.setBackgroundResource(R.drawable.textview_vehicle);
        } else if (daybooklist.getUsertype().startsWith("gsalary")) {
            day_usertype.setText("GS");
            day_usertype.setBackgroundResource(R.drawable.textview_worker);
        } else if (daybooklist.getUsertype().startsWith("isalary")) {
            day_usertype.setText("WS");
            day_usertype.setBackgroundResource(R.drawable.textview_worker);
        } else if (daybooklist.getUsertype().startsWith("payvehicle")) {
            day_usertype.setText("VP");
            day_usertype.setBackgroundResource(R.drawable.textview_vehicle);
        } else if (daybooklist.getUsertype().startsWith("buyer")) {
            day_usertype.setText("B");
            day_usertype.setBackgroundResource(R.drawable.textview_buyer);
        }
    }


    return convertView;
}

@Override
public int getChildrenCount(int groupPosition) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .size();
}

@Override
public Object getGroup(int groupPosition) {
    return this._listDataHeader.get(groupPosition);
}

@Override
public int getGroupCount() {
    return this._listDataHeader.size();
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    final String headerTitle = (String) getGroup(groupPosition);

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.model_daybook_group, null);
    }

    TextView lblListHeader = (TextView) convertView
            .findViewById(R.id.tv_daybook_date);
    final ImageView img_pdg = (ImageView) convertView.findViewById(R.id.img_printpdf);

    lblListHeader.setTypeface(null, Typeface.BOLD);
    lblListHeader.setText(headerTitle);
    String strDate = headerTitle;
    SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMMyyyy");
    try {
        Date varDate = dateFormat.parse(strDate);
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        updatedate = dateFormat.format(varDate);

    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    img_pdg.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    img_pdg.setColorFilter(ContextCompat.getColor(_context, R.color.colorAccent));

                    break;
                case MotionEvent.ACTION_UP:
                    img_pdg.clearColorFilter();
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                            _context);

                    // set title
                    alertDialogBuilder.setTitle(R.string.app_name);

                    // set dialog message
                    alertDialogBuilder
                            .setMessage(_context.getResources().getString(R.string.daybookreport) + headerTitle)
                            .setCancelable(true)
                            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // if this button is clicked, close
                                    // current activity
                                    Intent pdfreport = new Intent(_context, Activity_Daybookpdf.class);
                                    pdfreport.putExtra("date", updatedate);
                                    _context.startActivity(pdfreport);
                                }
                            })
                            .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // if this button is clicked, just close
                                    // the dialog box and do nothing
                                    img_pdg.clearColorFilter();
                                    dialog.cancel();

                                }
                            });

                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();

                    // show it
                    alertDialog.show();
                    Button nbutton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                    nbutton.setTextColor(_context.getResources().getColor(R.color.colorAccent));
                    Button pbutton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
                    pbutton.setBackgroundColor(_context.getResources().getColor(R.color.colorAccent));
                    pbutton.setPadding(0, 10, 10, 0);
                    pbutton.setTextColor(Color.WHITE);
                    break;
            }
            return true;


        }
    });
    convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            img_pdg.setColorFilter(ContextCompat.getColor(_context, R.color.colorAccent));
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    _context);

            // set title
            alertDialogBuilder.setTitle(R.string.app_name);

            // set dialog message
            alertDialogBuilder
                    .setMessage(_context.getResources().getString(R.string.daybookreport) + headerTitle)
                    .setCancelable(true)
                    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // if this button is clicked, close
                            // current activity
                            Intent pdfreport = new Intent(_context, Activity_Daybookpdf.class);
                            pdfreport.putExtra("date", updatedate);
                            _context.startActivity(pdfreport);
                        }
                    })
                    .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // if this button is clicked, just close
                            // the dialog box and do nothing
                            img_pdg.clearColorFilter();
                            dialog.cancel();

                        }
                    });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
            Button nbutton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
            nbutton.setTextColor(_context.getResources().getColor(R.color.colorAccent));
            Button pbutton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
            pbutton.setBackgroundColor(_context.getResources().getColor(R.color.colorAccent));
            pbutton.setPadding(0, 10, 10, 0);
            pbutton.setTextColor(Color.WHITE);
        }
    });
    return convertView;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

public void setTransactionList(List<String> newList, HashMap<String, List<Daybooklist>> childlist) {

    _listDataHeader.clear();
    _listDataChild.clear();
    _listDataHeader = newList;
    _listDataChild = childlist;
    notifyDataSetChanged();
}

public void setVTransactionList(List<String> newList) {
    _listDataHeader = newList;
    notifyDataSetChanged();
}


public void isScrolling(boolean isScroll) {
    isListScrolling = isScroll;
    Log.e("scrollcheck", String.valueOf(isListScrolling));
}

}

异步任务:

 class LoadDataTask extends AsyncTask<String, Void, String> {

    Daybooklist daybooklist = new Daybooklist();
    @Override
    protected String doInBackground(String... olimits) {
        String limits = null;
        kickstart = 2;
        olimit=20;
        Log.e("kickcheck", String.valueOf(kickstart));
        loadingMore = true;
        try {
            limits = olimits[0];
            Log.e("limitscheck",limits);
            daybooks = new ArrayList<Daybook>();
            daybooks = databaseHandler.getAlldaybookentriesdatewise(olimit);
            daybooklists = new ArrayList<Daybooklist>();


            listDataHeader = new ArrayList<String>();
            listDataChild = new HashMap<String, List<Daybooklist>>();

            for (int i = 0; i < daybooks.size(); i++) {
                String date = daybooks.get(i).getDate();
                if (date != null) {
                    String s = date;
                    String[] spiliter = s.split("-");
                    String year = spiliter[0];
                    String month = spiliter[1];
                    String dates = spiliter[2];
                    if (month.startsWith("01")) {
                        disorderedlist = dates + "Jan" + year;
                        disorderedlist = disorderedlist.replaceAll("\\s+", "");
                    } else if (month.startsWith("02")) {
                        disorderedlist = dates + "Feb" + year;
                        disorderedlist = disorderedlist.replaceAll("\\s+", "");
                    } else if (month.startsWith("03")) {
                        disorderedlist = dates + "Mar" + year;
                        disorderedlist = disorderedlist.replaceAll("\\s+", "");
                    } else if (month.startsWith("04")) {
                        disorderedlist = dates + "Apr" + year;
                        disorderedlist = disorderedlist.replaceAll("\\s+", "");
                    } else if (month.startsWith("05")) {
                        disorderedlist = dates + "May" + year;
                        disorderedlist = disorderedlist.replaceAll("\\s+", "");
                    } else if (month.startsWith("06")) {
                        disorderedlist = dates + "Jun" + year;
                        disorderedlist = disorderedlist.replaceAll("\\s+", "");
                    } else if (month.startsWith("07")) {
                        disorderedlist = dates + "Jul" + year;
                        disorderedlist = disorderedlist.replaceAll("\\s+", "");
                    } else if (month.startsWith("08")) {
                        disorderedlist = dates + "Aug" + year;
                        disorderedlist = disorderedlist.replaceAll("\\s+", "");
                    } else if (month.startsWith("09")) {
                        disorderedlist = dates + "Sep" + year;
                        disorderedlist = disorderedlist.replaceAll("\\s+", "");
                    } else if (month.startsWith("10")) {
                        disorderedlist = dates + "Oct" + year;
                        disorderedlist = disorderedlist.replaceAll("\\s+", "");
                    } else if (month.startsWith("11")) {
                        disorderedlist = dates + "Nov" + year;
                        disorderedlist = disorderedlist.replaceAll("\\s+", "");
                    } else if (month.startsWith("12")) {
                        disorderedlist = dates + "Dec" + year;
                        disorderedlist = disorderedlist.replaceAll("\\s+", "");
                    }
                    listDataHeader.add(disorderedlist);
                }

                chid = new ArrayList<Daybooklist>();
                daybooklists = databaseHandler.getAllDaywisedaybookdetails(date);
                for (int j = 0; j < daybooklists.size(); j++) {


                    String name = daybooklists.get(j).getName();
                    String desc = daybooklists.get(j).getDescription();
                    String type = daybooklists.get(j).getType();
                    String usertype = daybooklists.get(j).getUsertype();
                    String amtin = daybooklists.get(j).getAmountin();
                    String amtout = daybooklists.get(j).getAmountout();
                    String extamt = daybooklists.get(j).getExtraamt();
                    String mobno = daybooklists.get(j).getMobileno();
                    String dates = daybooklists.get(j).getSdate();
                    String time = daybooklists.get(j).getCtime();


                    if (name != null) {
                        chid.add(new Daybooklist(name, desc, type, usertype, amtin, amtout, extamt, mobno, dates, time));

                    }

                }


                listDataChild.put(listDataHeader.get(i), chid);


            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        return disorderedlist;
    }

    @Override
    protected void onPostExecute(String disorderedlist) {
       // listAdapter = new DaybookExpandableAdapter(getApplicationContext(), listDataHeader, listDataChild);

          listAdapter.setTransactionList(listDataHeader,listDataChild);
        loadingMore = false;
    }

    @Override
    protected void onCancelled() {
        // Notify the loading more operation has finished
        loadingMore = false;
    }
}

适配器通知:

  public void setTransactionList(List<String> newList, HashMap<String, List<Daybooklist>> childlist) {

    _listDataHeader.clear();
    _listDataChild.clear();
    _listDataHeader = newList;
    _listDataChild = childlist;
    notifyDataSetChanged();
}

数据库:

  public ArrayList<Daybook> getAlldaybookentriesdatewise(int s) {
    ArrayList<Daybook> daybookDetails = new ArrayList<Daybook>();
    String selectquery = "SELECT date,IFNULL(SUM(amountin),0) as amountin,IFNULL(SUM(amountout),0) as amountout,daybookusertype FROM daybookdetails GROUP BY strftime('%Y-%m-%d',date) ORDER BY strftime('%Y-%m-%d',date) DESC LIMIT " + s + "";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectquery, null);
    if (cursor.moveToFirst()) {
        do {
            Daybook daybookentries = new Daybook();
            daybookentries.setDate(cursor.getString(0));
            daybookentries.setCashin(cursor.getString(1));
            daybookentries.setCashout(cursor.getString(2));
            daybookDetails.add(daybookentries);


        } while (cursor.moveToNext());

    }
    cursor.close();
    db.close();
    return daybookDetails;
}

我已经尝试过使用notifydatasetchanged但它没有用。

1 个答案:

答案 0 :(得分:0)

您需要在onPostExecute()方法中的视图中设置适配器:

protected void onPostExecute(String disorderedlist) {
    listAdapter = new DaybookExpandableAdapter(getApplicationContext(), listDataHeader, listDataChild);
    listView.setAdapter(listAdapter);
    listAdapter.setTransactionList(listDataHeader,listDataChild);
    loadingMore = false;
}