数据装入头和子列表 [英] Loading data to header and child list

查看:149
本文介绍了数据装入头和子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据加载到扩展列表视图,mProductList包含所有数据应该装载到头和子列表。我已加载的数据头列表。但我不知道如何将数据加载到子列表中。我已经使用这个教程做我的扩展列表视图( HTTP: //www.androidhive.info/2013/07/android-expandable-list-view-tutorial/ )。

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/).

任何人都可以指导我怎么能实现它吧。任何帮助将AP preciated。

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

更新时间:

ProductAdapter.java

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

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

}

屏幕截图

推荐答案

惠那里,我很少在一个月前完成这个任务,
我在做相应我的回答改变。

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

我在GSON的方式工作,请与本之一,也是为我工作试试。

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

这是一个JSONParser类

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

        }

    }

}

这是我的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三年级学生,获得更少的时间做研究我的职业道路发展,通常是在统一的工作保持忙碌:!/

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 :/.!

这篇关于数据装入头和子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆