Loading data to header and child list
Asked Answered
G

2

0

I want to load data into expandable list view, mProductList contains all the data should load to header and child list. I have loaded the data to header list. But I don't know how to load the data to child list. I have used this tutorial to do my expandable list view (http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/).

Can anyone guide me how can I achieve it please. Any help will be appreciated.

UPDATED

ProductAdapter.java

public class ProductAdapter extends BaseExpandableListAdapter {

    private Context _context;
    private List<String> _listDataHeader;
    private LayoutInflater mInflater;
    private boolean mShowQuantity;
    private HashMap<String, List<String>> _listDataChild;

    public ProductAdapter(Context context, List<String> listDataHeader,
            LayoutInflater inflater,
            HashMap<String, List<String>> listChildData, boolean showQuantity) {
        this._context = context;
        this._listDataHeader = listDataHeader;
        mInflater = inflater;
        mShowQuantity = showQuantity;
        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);

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

        TextView txtListChild = (TextView) convertView
                .findViewById(R.id.lblListItem);

        txtListChild.setText(childText);
        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) {
        String headerTitle = (String) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.cart_list_group, null);
        }

        TextView lblListHeader = (TextView) convertView
                .findViewById(R.id.lblListHeader);
        lblListHeader.setTypeface(null, Typeface.BOLD);
        lblListHeader.setText(headerTitle);

        return convertView;
    }

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

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

}

Shoppingcart.java

mCartList = ShoppingCartHelper.getCartList();

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

List<String> listdescription = new ArrayList<String>();
List<String> listcrust = new ArrayList<String>();
List<String> listsize = new ArrayList<String>();
List<String> listDescriptionOne = new ArrayList<String>();
List<String> listDescriptionTwo = new ArrayList<String>();
List<String> listDescriptionHalf = new ArrayList<String>();
List<String> listExtracheese = new ArrayList<String>();

String description;
String crust;

// Make sure to clear the selections
for (int i = 0; i < mCartList.size(); i++) {

    mCartList.get(i).selected = false;
    hot_number = mCartList.size();

    if (mCartList.get(i).description != null
            && !mCartList.get(i).description.isEmpty()) {
        description = mCartList.get(i).description;

        listdescription.add(description);
        System.out.println("listdescription = " + listdescription);
    }

    if (mCartList.get(i).crust != null
            && !mCartList.get(i).crust.isEmpty()) {
        crust = mCartList.get(i).crust;

        listcrust.add(crust);
        System.out.println("listcrust = " + listcrust);
    }

}

listDataChild.put("listcrust", listcrust);

listDataHeader.addAll(listdescription);

// get the listview
expListView = (ExpandableListView) findViewById(R.id.lvExp);

mProductAdapter = new ProductAdapter(this, listDataHeader,
        getLayoutInflater(), listDataChild, true);      

// setting list adapter
expListView.setAdapter(mProductAdapter);

}

Screenshot

enter image description here

Grudging answered 24/3, 2015 at 11:14 Comment(10)
If my answer helped kindly response.Winterfeed
Yh sure, I'm sill trying that and I'm getting some errors, i'll Update u soonGrudging
kindly post errors , i will help, look make separate Mapper classes for Header data and Child data you made only one class that is why u r geting problem.Winterfeed
I'll update u complete code so u can guide me. But give me sometime pleaseGrudging
Oh , ok ok buddy, no problem :)Winterfeed
@M Faisal Hyder I have updated my complete code and I have shown the errors I'm getting. Can u take a look at it. If u suggest any new way of doing the complete thing please suggest me.Grudging
hey my friend, look , i didn't say to initialize your same Product class with different object names, u have to make different class for Header data and Child data i am updating my answer to complete project code.! May be that will help.Winterfeed
ok.. I'm waiting for your answerGrudging
I updated my answer to simpler way to achieve task kindly have a look , take your time and tell. :)Winterfeed
sre ill try this out and update youGrudging
W
1

Hye there , i achieved this task little a month ago, I made changes in my answer accordingly.

I am working on GSON way , kindly try with this one it is also working for me.

This is a JSONParser Class

public class JSONParser {

static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";

public JSONParser() {
}

public JSONArray getJSONFromUrl(String url) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e("==>", "Failed to download file");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } // Parse String to JSON object
    try {
        jarray = new JSONArray(builder.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    } // return JSON Object
    return jarray;
   }

}

Now use it in your main activity like this i have used.

public class Main extends ExpandableListActivity {

Button btnGET;
JSONParser jp;
JSONObject jsonObject = new JSONObject();
JSONArray jarray = new JSONArray();
ExpandableListView elv;
ProgressDialog pd;

List<HashMap<String, String>> parent = new ArrayList<HashMap<String, String>>();
List<List<HashMap<String, String>>> child = new ArrayList<List<HashMap<String, String>>>();

private static String URL = "http://192.168.0.100:7001/com.faisal.REST_WS/api/v1/json";
private static final String Name = "Name";
private static final String IDNumber = "IDNumber";
private static final String FatherName = "FatherName";
private static final String Occupation = "Occupation";
private static final String Age = "Age";
private static final String MartialStatus = "MartialStatus";
private static final String UserStatus = "UserStatus";
private static final String DateOfBirth = "DateOfBirth";
private static final String Brand = "Brand";

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnGET = (Button) findViewById(R.id.btn_GET);
    btnGET.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            APICaller caller = new APICaller();
            caller.execute();
        }
    });

}

private class APICaller extends AsyncTask<String, Void, Boolean> {

    // private Context context;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // pDialog = ProgressDialog.show(Main.this,"", "Getting data...");
        pd = new ProgressDialog(Main.this);
        pd.setMessage("Getting Data ...");
        pd.setIndeterminate(false);
        pd.setCancelable(true);
        pd.show();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        JSONParser jp = new JSONParser();
        JSONArray jarray = jp.getJSONFromUrl(URL);
        try {
            for (int i = 0; i < jarray.length(); i++) {
                HashMap<String, String> mapparent = new HashMap<String, String>();
                List<HashMap<String, String>> mapchild = new ArrayList<HashMap<String, String>>();
                HashMap<String, String> minimapchild = new HashMap<String, String>();

                JSONObject jsonObject = jarray.getJSONObject(i);

                mapparent.put("IDNumber", jsonObject.getString("IDNumber"));
                parent.add(mapparent);

                // jsonObject = jarray.getJSONObject(i);

                minimapchild.put("Name", jsonObject.getString("Name"));
                minimapchild.put("FatherName",
                        jsonObject.getString("FatherName"));
                minimapchild.put("Occupation",
                        jsonObject.getString("Occupation"));
                minimapchild.put("Age", jsonObject.getString("Age"));
                minimapchild.put("MartialStatus",
                        jsonObject.getString("MartialStatus"));
                minimapchild.put("Brand", jsonObject.getString("Brand"));
                minimapchild.put("UserStatus",
                        jsonObject.getString("UserStatus"));
                minimapchild.put("DateOfBirth",
                        jsonObject.getString("DateOfBirth"));

                mapchild.add(minimapchild);
                child.add(mapchild);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        if (pd.isShowing()) {
            pd.cancel();
        }

        ExpandableListAdapter adapter = new SimpleExpandableListAdapter(
                getApplicationContext(), parent, R.layout.parent_row,
                new String[] { IDNumber }, new int[] { R.id.idn }, child,
                R.layout.child_row, new String[] { Name, FatherName, Age,
                        Occupation, MartialStatus, UserStatus, Brand,
                        DateOfBirth }, new int[] { R.id.name, R.id.fn,
                        R.id.Occup, R.id.M_S, R.id.U_S, R.id.brand,
                        R.id.age, R.id.DofB });
        setListAdapter(adapter);
        elv = getExpandableListView();

        }

    }

}

This is my JSON

[
 {
 "IDNumber": 2,
 "Name": "PDP",
 "FatherName": "DER",
 "Age": "AA",
 "DateOfBirth": "16th Nov YYYY",
 "Occupation": "Senior .NET Dev",
 "MartialStatus": "UnMarried",
 "Brand": "YYZ",
 "UserStatus": "Family"
 },
 {
 "IDNumber": 3,
 "Name": "EWR",
 "FatherName": "GRT",
 "Age": "AA",
 "DateOfBirth": "16th May YYYY",
 "Occupation": "Executive Shu Shef",
 "MartialStatus": "Married",
 "Brand": "XXX",
 "UserStatus": "Family"
 },
]

This is the simplest way to achieve but it is lengthy, i am working on GSON , will update my answer to GSON expandable way soon, actually, i myself a UNI 3rd year student, get less time to do study my career path development and usually stay busy in Uni work :/.!

Winterfeed answered 24/3, 2015 at 14:29 Comment(5)
I'm working on this, can I get the SimpleExpandableListAdapter as well please. Bit confused in loading the dataGrudging
hye, simple expandable is provided by Android as built in.! :)Winterfeed
hey can u check my updated question. It crashes when I press on the group list view. Screen shot shows where it crashes and value for _listDataChild when it crashes. You have any idea why does it go wrongGrudging
Thanks alot bro.. U gave me a perfect start and finally I have achieved it :). this tutorial also helped me alot... survivingwithandroid.com/2013/01/…Grudging
thank you buddy :) happy coding :) and one thing also try to learn and understand things how can i do this , that, etc. 1- make a sketch in your mind to cope with your problem. 2- start developing in that way to solve your problem :) Update your question with your answer(working code) .!Winterfeed
S
0

try this , update your getChildView() method as follows ,

 final String childText = (String) this._listDataChild.get(this.mProductList.get(groupPosition))
            .get(childPosititon);
Sarette answered 24/3, 2015 at 11:41 Comment(1)
I'm getting a null point exception, I have shown in the comment where I'm getting it. You have any idea where i"m going wrongGrudging

© 2022 - 2024 — McMap. All rights reserved.