Frage

Senior Geeks.

I'd like to request a simple but fully working example of how to implement an ExpandableListView while extending from BaseExpandableListAdapter Yet Reading data from an Sqlite Database.

I have researched and experimented on the question (see here), but with minimal success where i was able to display some data in the header, albeit it was same values repeating for all group headers. Also child items don't show.

The reason for extending with BaseExpandableListAdapter is to have a custom layout for the group header. The reason for SQLite access is naturally because thats where my data is stored.

All examples trawled on the net so far use either SimpleCursorTreeAdapter or CursorTreeAdapter as the extender in DB based applications or simply BaseExpandableListAdapter when data used is in ArrayLists.

Below is the Experimentation thus far. (with this code,only the group header is populated with the same figures over and over. Childitems dont appear)

public class ExpandableListViewAdapterCustom extends BaseExpandableListAdapter {
    protected Activity currentActivity;
    public ExpandableListViewAdapterCustom(Activity callingActivity){
    this.currentActivity = callingActivity;
    }

    private Cursor mGroupsCursorLocal ;
    private Cursor mChildCursor;
    private Context ctx;
    private int groupItem;
    private int childItem;
    private String[] fieldsToUseFromGroupCursor;
    private int[] screenTextsToMapGroupDataTo;
    private String[] fieldsToUseFromChildCursor;
    private int[] screenTextsToMapChildDataTo;

    public ArrayList<String> tempChild;
    public LayoutInflater minflater;
    public Activity activity;
    public int intGroupTotal;


    public void setCurrentActivity(Activity activity) {
       this.activity = activity;
    }

    public void setCtx(Context ctx) {
       this.ctx = ctx;
    }

     public void setGroupItem(int groupItem) {
         this.groupItem = groupItem;
      }

    public void setChildItem(int childItem) {
        this.childItem = childItem;
    }

    public Activity getCurrentActivity() {
        return currentActivity;
    }

     public Cursor getmGroupsCursorLocal() {
        return mGroupsCursorLocal;
      }

    public Context getCtx() {
        return currentActivity.getBaseContext();
    }

    public void setmGroupsCursorLocal(Cursor mGroupsCursor) {
        this.mGroupsCursorLocal = mGroupsCursor;
    }

    public ExpandableListViewAdapterCustom(Cursor mGroupsCursor,
                                       Activity activity,
                                       int groupItem,
                                       int childItem,
                                       String[] fieldsToUseFromGroupCursor,
                                       int[] screenTextsToMapGroupDataTo,
                                       String[] fieldsToUseFromChildCursor,
                                       int[] screenTextsToMapChildDataTo) {



        DatabaseRoutines db = new DatabaseRoutines(activity);

        setmGroupsCursorLocal(mGroupsCursor);
        mGroupsCursorLocal = db.fetchGroup();
        activity.startManagingCursor (mGroupsCursor);
        mGroupsCursorLocal.moveToFirst();

        mChildCursor=db.fetchChildren(mGroupsCursorLocal.getColumnIndex("Year"));
        mChildCursor.moveToFirst();
        activity.startManagingCursor(mChildCursor);



        setCtx(activity);
        setCurrentActivity(activity);

        }

        public void setInflater(LayoutInflater mInflater, Activity act) {
        this.minflater = mInflater;
        activity = act;
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
           return null;
        }

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


        @Override
        public View getChildView(int groupPosition, 
            int childPosition,boolean         
            isLastChild, 
            View convertView, 
            ViewGroup parent) {
           View v = convertView;
           if (v == null) 
        {
        LayoutInflater inflater = 
       (LayoutInflater)     ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);            
       v = inflater.inflate(R.layout.exp_listview_childrow, parent, false);
        }

        TextView txtMonth = (TextView) v.findViewById(R.id.txtMonth);
        TextView txtMonthAmountSent = (TextView)
        v.findViewById(R.id.txtMonthAmountSentValue);
        TextView txtMonthReceived = (TextView)
        v.findViewById(R.id.txtMonthAmountReceivedValue);
        txtMonth.setText(mChildCursor.getString(mChildCursor.getColumnIndex("Month")));

    txtMonthAmountSent.setText
   (mChildCursor.getString(mChildCursor.getColumnIndex("TotalSent")));
    txtMonthReceived.setText

    (mChildCursor.getString(mChildCursor.getColumnIndex("TotalReceived")));
    return v;
     }


    @Override
    public int getChildrenCount(int groupPosition) {
        return (mChildCursor.getCount());
       }

    @Override
     public Object getGroup(int groupPosition) {
     return null;
    }

    @Override
    public int getGroupCount() {
    return mGroupsCursorLocal.getCount();
    }

    @Override
    public void onGroupCollapsed(int groupPosition) {
    super.onGroupCollapsed(groupPosition);
    }

    @Override
     public void onGroupExpanded(int groupPosition) {
    super.onGroupExpanded(groupPosition);
    }

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


    @Override
    public View getGroupView(
       int groupPosition, 
       boolean isExpanded,
       View convertView,     
       ViewGroup parent) 
     {
         View v = convertView;
         if (v == null) {
        LayoutInflater inflater =  
        (LayoutInflater)  ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.exp_listview_groupheader, parent, false);
       }

       TextView txtYear = (TextView) v.findViewById(R.id.txtYearValue);
       TextView txtAmountSent = (TextView) v.findViewById(R.id.txtAmountSentValue);
       TextView txtAmountRecieved = (TextView) 
       v.findViewById(R.id.txtAmountReceivedValue);

       txtYear.setText(mGroupsCursorLocal.getString(
       mGroupsCursorLocal.getColumnIndex("Year")));

       txtAmountSent.setText(
       mGroupsCursorLocal.getString(mGroupsCursorLocal.getColumnIndex("TotalSent")));

       txtAmountRecieved.setText(
      GroupsCursorLocal.getString(mGroupsCursorLocal.getColumnIndex("TotalReceived")));
      return v;
    }

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

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


}

The Database code is like this

public Cursor fetchGroup() {
    SQLiteDatabase db = this.getReadableDatabase();  //if memory leaks check here
        String query = "SELECT DISTINCT MIN(ID) AS id, 
    Year, SUM(SentAmount) AS    TotalSent, SUM(ReceivedAmount) AS TotalReceived 
     FROM  MyTbl GROUP BY Year ORDER BY Year DESC ";
      return db.rawQuery(query, null);}

public Cursor fetchChildren(int Yr) {
    SQLiteDatabase db = this.getReadableDatabase(); //if memory leaks check here
    String query = "SELECT  MIN(ID) AS id, 
    Year, Month, SUM(SentAmount) AS TotalSent, 
     SUM(ReceivedAmount) AS TotalReceived        
     FROM  MyTbl Where Year= "+ Yr +"   GROUP BY Year, 
     Month ORDER BY Year DESC, Month DESC";
    return db.rawQuery(query, null);
   } 

The Code is called from main activity using the following

    ExpandableListView elv = (ExpandableListView)    

    findViewById(R.id.expandableListView);
       ExpandableListAdapter mAdapter = new 
       ExpandableListViewAdapterCustom(mGroupsCursor,    
       MyActivity.this,
            R.layout.exp_listview_groupheader,// Your row layout   for a group
            R.layout.exp_listview_childrow, // Your row layout for a child
            new String[] { "Year",
            "TotalSent",
            "TotalReceived" },// Field(s) to use from group cursor       
            new int[] {R.id.txtYearValue,
                       R.id.txtAmountSentValue,
                       R.id.txtAmountReceivedValue },// Widget ids to put group data                        
                       into new String[] { "Year","Month", 
                       "TotalSent", 
                       "TotalReceived" },  // Field(s) to use from child cursors  new  
                        int[] {R.id.txtMonthValue,
                        R.id.txtMonthAmountSentValue,
                        R.id.txtMonthAmountReceivedValue});// Widget ids to put child d   
                        data into
                        elv.setClickable(true);
                        elv.setAdapter(mAdapter); // set the
War es hilfreich?

Lösung

After almost two weeks and no answer, i decided to simply use an ExpandableListView example using ArrayLists and modified it such that the ArrayLists were populated by data from the DB. Its not what i wanted but it works. I was actually suprised that nowhwere on the web is there an example of using ExpandableListview extended form BaseAdapter but reading from SQlite using say cursorTreeAdapter or SimpleCursorAdapter. Below is how i did it in case it helps someone in future. the code shown is the bit that populates the ArrayList from DB

public ArrayList<ExpandListGroup> SetStandardGroups() {

    ArrayList<ExpandListGroup> list = new ArrayList<ExpandListGroup>();
    ArrayList<ExpandListChild> list2 = new ArrayList<ExpandListChild>();
    int intMonthNum;
    ExpandListGroup grp;
    ExpandListChild chld;

    //initialize db code here
    DatabaseRoutines db = new DatabaseRoutines(this);

    //create the Groups retreival cursor;
    Cursor mGroupsCursor = db.fetchGroup();

    //---the database call is done using this code which is in my 
    //---custom db class which implements the sqlhelper methods etc
    //------start of db code snippet------------------------------- 
    //---public Cursor fetchGroup() {
    //---SQLiteDatabase db = this.getReadableDatabase();
    //--- String query = "SELECT DISTINCT MIN(ID) AS id, Year, 
    //--- SUM(SentAmount) AS TotalSent, 
    //--- SUM(ReceivedAmount) AS TotalReceived 
    //--- FROM  Tbl GROUP BY Year ORDER BY Year DESC ";
    //--- return db.rawQuery(query, null);}
    //------end of db code snippet-------------------------------
    mGroupsCursor.moveToFirst();

    //method is depreciated from api14 but i'm targeting Gingerbread (api10) so i need to use it.
    startManagingCursor(mGroupsCursor);
    int intYear;
    int intHeaderCounter = 0;
    int intChildCounter = 0;
    int intChildTotalCount = 0;
    int intHeaderTotalGroupCount = mGroupsCursor.getCount();

    //set the starting Year for the loop, if there is data;
    if (intHeaderTotalGroupCount > 0) {
        //get the first year
        //intYear = mGroupsCursor.getInt(mGroupsCursor.getColumnIndex("Year"));

        for (intHeaderCounter = 0; intHeaderCounter < intHeaderTotalGroupCount; intHeaderCounter++) {

            grp = new ExpandListGroup();
            intYear = mGroupsCursor.getInt(mGroupsCursor.getColumnIndex("Year"));
            grp.setYear(intYear);
            grp.setYearAmountReceived(mGroupsCursor.getDouble(mGroupsCursor.getColumnIndex("TotalReceived")));
            grp.setYearAmountSent(mGroupsCursor.getDouble(mGroupsCursor.getColumnIndex("TotalSent")));
            grp.setTag(mGroupsCursor.getString(mGroupsCursor.getColumnIndex("id")));


            //Prepare counters for inner loop for child items of each
            Cursor mChildCursor = db.fetchChildren(intYear);
            mChildCursor.moveToFirst();
            intChildTotalCount = mChildCursor.getCount();
            //populate child items
            for (intChildCounter = 0; intChildCounter < intChildTotalCount; intChildCounter++) {
                chld = new ExpandListChild();
                intMonthNum = mChildCursor.getInt(mChildCursor.getColumnIndex("Month"));
                chld.setMonthNumber(intMonthNum);
                chld.setTotalReceivedMonth(mChildCursor.getInt(mChildCursor.getColumnIndex("TotalReceived")));
                chld.setTotalSentMonth(mChildCursor.getInt(mChildCursor.getColumnIndex("TotalSent")));
                chld.setTag(mGroupsCursor.getString(mGroupsCursor.getColumnIndex("id")).toString());

                list2.add(chld);
                //grp.setItems(list2);
                //move to next child record;

                mChildCursor.moveToNext();


            }


            grp.setItems(list2);
            list.add(grp);

            list2 = new ArrayList<ExpandListChild>();
            //move to next parent record;
            mGroupsCursor.moveToNext();

        }

    } else {
        log.d( "yourdebugtag_here", "Sorry, No Transactions Found.");
    }

    //db.close();


    return list;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top