将数据加载到标题和子列表

时间:2015-03-24 11:14:44

标签: android expandablelistview

我想将数据加载到可扩展列表视图中,mProductList包含应加载到头和子列表的所有数据。我已将数据加载到标题列表。但我不知道如何将数据加载到子列表。我已经使用本教程来执行可扩展列表视图(http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/)。

任何人都可以指导我如何实现它。任何帮助将不胜感激。

更新

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

}

截图

enter image description here

2 个答案:

答案 0 :(得分:1)

是的,我在一个月前完成了这个任务, 我相应地修改了答案。

我正在研究GSON方式,请尝试使用这个方法,它也适用于我。

这是一个JSONParser类

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

}

现在在我使用过的主要活动中使用它。

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

        }

    }

}

这是我的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"
 },
]

这是最简单的实现方式,但是它很长,我正在研究GSON,很快就会更新我对GSON可扩展方式的回答,实际上,我自己是UNI三年级学生,花更少的时间去研究我的职业道路开发并且通常在Uni工作中忙碌:/。!

答案 1 :(得分:0)

试试这个,按如下方式更新你的getChildView()方法,

 final String childText = (String) this._listDataChild.get(this.mProductList.get(groupPosition))
            .get(childPosititon);