简体   繁体   English

滚动到达结束时如何在android expandable listview中使用Loadmore数据

[英]How to use Loadmore data in android expandable listview when scroll reaches end

I am creating an android application in which i have used expandable listview in which i would like to set a limit to show only 10 datas at first in the expandable listview.once the listview reaches end it will load another 10 datas from the database for which the loading the data for group works fine but for the child view it is not working properly can any one tell me how to make the childview to show the loaded item in the expandable listview. 我正在创建一个Android应用程序,其中我使用了可扩展的listview,其中我想设置一个限制,在可扩展listview中首先只显示10个数据。在listview到达end它将从数据库加载另外10个数据加载组的数据工作正常,但对于子视图,它不能正常工作,任何人都可以告诉我如何使子视图在可扩展列表视图中显示加载的项目。

Background process which loads data: 加载数据的后台进程:

private class LoadDataTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loadingMore = true;
        // showDialog(progress_bar_type);
    }

    @Override
    protected Void doInBackground(Void... params) {

        if (isCancelled()) {
            return null;
        }
        Log.e("test2", "reached");
        // Simulates a background task
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }


        Log.e("test3", "starting");
        databasehandler = new DatabaseHandler(getApplicationContext());
        if (olimit > totalcount) {
            // olimit = 1;
            // olimit = 2;
        } else {
            olimit = olimit + 10;


        }
        listDataHeader = new ArrayList<String>();
        databasehandler = new DatabaseHandler(getApplicationContext());

        listDataHeader = new ArrayList<String>();
        String selectquery = "SELECT date,IFNULL(SUM(amountin),0) as amountin,IFNULL(SUM(amountout),0),daybookusertype as amountout FROM daybookdetails GROUP BY strftime('%Y-%m-%d',date) ORDER BY strftime('%Y-%m-%d',date) DESC LIMIT '" + olimit + "'";
        SQLiteDatabase db = databasehandler.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectquery, null);
        if (cursor.moveToFirst()) {
            do {
                loadeddate = cursor.getString(0);

                String s = loadeddate;
                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(loadeddate);
                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 datess = daybooklists.get(j).getSdate();
                    String time = daybooklists.get(j).getCtime();
                    Log.e("ctime", time);
                    chid.add(new Daybooklist(name, desc, type, usertype, amtin, amtout, extamt, mobno, datess, time));
                }

                listDataChild.put(String.valueOf(listDataHeader), chid);

            } while (cursor.moveToNext());

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


        return null;

    }

    @Override
    protected void onPostExecute(Void result) {

        listAdapter.setTransactionList(listDataHeader, listDataChild);


        loadingMore = false;
        //  dismissDialog(progress_bar_type);

        super.onPostExecute(result);
    }

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

Expandable ListAdapter: 可扩展的ListAdapter:

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
                                    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;


        }
    });
    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 = newList;
    _listDataChild = childlist;

    notifyDataSetChanged();
}



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

} }

Problem: 问题:

  listDataChild.put(String.valueOf(listDataHeader), chid);

can anyone tell me what i have to change over here 任何人都可以告诉我我必须在这里改变什么

try this may help you : 试试这可能对你有所帮助:

  1. at first define this variable to save states : 首先定义此变量以保存状态:

      private boolean loadMore = true; private int pastVisiblesItems, visibleItemCount, totalItemCount; 
  2. then set scroll listener for listView : 然后为listView设置滚动侦听器:

      listView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int i) { } @Override public void onScroll(AbsListView absListView, int i, int i1, int i2) { visibleItemCount = listView.getChildCount(); totalItemCount = listView.getCheckedItemCount(); pastVisiblesItems = listView.getFirstVisiblePosition(); if (loadMore) { if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) { soundListSearch.add(null); new LoadDataTask().execute(); } } } }); 
  3. And finally loadMore=false ever that you want to prevent load more data(for example when catch exception in AsyncTask or data query ended or....) 最后loadMore=false ,你想要阻止加载更多数据(例如当AsyncTask中的catch异常或数据查询结束时......)


Edit 1 for adding to listDataChild HashMap 编辑1以添加到listDataChild HashMap

no , it's not correct. 不,这不对。 you should use like this 你应该这样用

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

because first value of listDataChild should be string type but you try set a arrayList 因为listDataChild第一个值应该是string type但是您尝试设置一个arrayList

for add all items of listDataChild into listDataChild do this : listDataChild所有项添加到listDataChild执行以下操作:

  for (int i =0 ; i<listDataHeader.size();i++)
    {
         listDataChild.put(listDataHeader.get(i), chid); 
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM