如何在viewpager中动态加载JSON数据并设置为expandablelistview

时间:2015-03-04 11:59:31

标签: android json android-viewpager expandablelistview

我的Json数据(1页链接)http://192.168.0.2/AIRIS/api/Main/GetCateenOrderCategoryItemListDetail?CategoryID=35

    {
    "SBL": [
        {
            "SubCategoryID": 37,
            "SubCategoryName": "Buscuites",
            "SubCategoryItemList": [
                {
                    "ItemID": 23,
                    "SubCategoryID": 37,
                    "ItemName": "Orio Buscuites",
                    "ImageUrl": "http://192.168.0.222/HRISWebAPI/ClientResources/CntRowMaterial/23.jpg",
                    "Qty": 1,
                    "DefaultPrice": 10,
                    "Price": null,
                    "Discount": null,
                    "FinalPrice": 10
                },
                {
                    "ItemID": 29,
                    "SubCategoryID": 37,
                    "ItemName": "Parle-G",
                    "ImageUrl": "http://192.168.0.222/HRISWebAPI/ClientResources/CntRowMaterial/29.jpg",
                    "Qty": 1,
                    "DefaultPrice": 5,
                    "Price": null,
                    "Discount": null,
                    "FinalPrice": 5
                },
                {
                    "ItemID": 30,
                    "SubCategoryID": 37,
                    "ItemName": "BornBorn",
                    "ImageUrl": "http://192.168.0.222/HRISWebAPI/ClientResources/CntRowMaterial/30.jpg",
                    "Qty": 1,
                    "DefaultPrice": 25,
                    "Price": null,
                    "Discount": null,
                    "FinalPrice": 25
                },
                {
                    "ItemID": 31,
                    "SubCategoryID": 37,
                    "ItemName": "Hide & Sick",
                    "ImageUrl": "http://192.168.0.222/HRISWebAPI/ClientResources/CntRowMaterial/31.jpg",
                    "Qty": 1,
                    "DefaultPrice": 20,
                    "Price": null,
                    "Discount": null,
                    "FinalPrice": 20
                }
            ]
        },
        {
            "SubCategoryID": 38,
            "SubCategoryName": "Tea",
            "SubCategoryItemList": [
                {
                    "ItemID": 18,
                    "SubCategoryID": 38,
                    "ItemName": "Ice Tea",
                    "ImageUrl": "http://192.168.0.222/HRISWebAPI/ClientResources/CntRowMaterial/18.jpg",
                    "Qty": 1,
                    "DefaultPrice": 0,
                    "Price": null,
                    "Discount": null,
                    "FinalPrice": 0
                },
                {
                    "ItemID": 19,
                    "SubCategoryID": 38,
                    "ItemName": "Lempon Tea",
                    "ImageUrl": "http://192.168.0.222/HRISWebAPI/ClientResources/CntRowMaterial/19.jpg",
                    "Qty": 1,
                    "DefaultPrice": 20,
                    "Price": null,
                    "Discount": null,
                    "FinalPrice": 20
                }
            ]
        }
    ]
}

如何加载JSON数据并设置为expandablelistview,它放置在viewpager的每个页面上,其中数据动态地设置expandablelistview使用android中的getter和setter mehod

TabMenuActivity.java(扩展了ActinBarActivity) 从这个类controll传递活动到片段,如下所示onPostExecute()的类方法

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        dialog.dismiss();
        if(result == true){
            if (categoryList.size() > 0) {

                AppConstants.CATEGORY_LIST = categoryList;

                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                SlidingContentFragment fragment = new SlidingContentFragment();
                transaction.replace(R.id.sample_content_fragment, fragment);
                transaction.commit();
            }
        }
        else{
            Toast.makeText(getApplicationContext(), "CategoryListJSONAsyncTask:Unable to fetch data", Toast.LENGTH_SHORT).show();
        }
    }

SlidingContentFragment.java(此类扩展片段)

注意:在instantiateItem()方法的子类SamplePagerAdaptor.java的这个类方法中,我将ExpandableListview用于显示数据。

public class SlidingContentFragment extends Fragment {
    static final String LOG_TAG = "SlidingContentFragment";

// store category list from Conastant list, used for to display pagetitle

List<String> catList = AppConstants.CATEGORY_LIST;
private static String[] tmpId  = {"35","36","41","42","43","44","45","46"};

ExpandableListView exListCategory;


private SlidingTabLayout mSlidingTabLayout;

/**
 * A {@link android.support.v4.view.ViewPager} which will be used in conjunction with the {@link SlidingTabLayout} above.
 */
private ViewPager mViewPager;
//private ExpandableListAdapter mAdapter; // added new
private SamplePagerAdapter myAdapter;

public SlidingContentFragment() {
}



@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View slideRootView =  inflater.inflate(R.layout.fragment_sliding_content, container, false);

    return slideRootView;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // BEGIN_INCLUDE (setup_viewpager)
    // Get the ViewPager and set it's PagerAdapter so that it can display items
    this.myAdapter = new SamplePagerAdapter(); // added new
    mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
    mViewPager.setAdapter(this.myAdapter);
    // END_INCLUDE (setup_viewpager)



    // BEGIN_INCLUDE (setup_slidingtablayout)
    // Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
    // it's PagerAdapter set.
    mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
    mSlidingTabLayout.setViewPager(mViewPager);

}

public class SamplePagerAdapter extends PagerAdapter {


    // This holds all the currently displayable views, in order from left to right.
    private ArrayList<View> views = new ArrayList<View>();

    @Override
    public int getCount() {
        return catList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object o){
        return o == view;
    }


    @Override
    public CharSequence getPageTitle(int position) {
       return catList.get(position);
    }


    @Override
    public int getItemPosition (Object object)
    {
        int index = views.indexOf (object);
        if (index == -1)
            return POSITION_NONE;
        else
            return index;
    }


    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        //return super.instantiateItem(container, position);
        View view = getActivity().getLayoutInflater().inflate(R.layout.pager_item,
                container, false);
        container.addView(view);
        //ListView listCategory = (ListView) v.findViewById(R.id.listView);
        exListCategory = (ExpandableListView)view.findViewById(R.id.myExpandableListView);

        new CategoryJSONAsyncTask().execute("http://192.168.0.2/AIRIS/api/Main/GetCateenOrderCategoryItemListDetail?CategoryID="+tmpId[position].toString().trim());

        Log.i("POSITION", String.valueOf(position));
        Log.i("catList",String.valueOf(catList.get(position)));

        return view;

    }


    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((View) object);
    }


}

public class CategoryJSONAsyncTask  extends AsyncTask<String,Void,String> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String result = "";
        try {
            HttpGet httppost = new HttpGet(params[0]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);

            // StatusLine stat = response.getStatusLine();
            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);

                return result;
            }
            return result;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

        @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
            ArrayList<CategoryParentItemList> listParent = fetchResponse(result.replace("\n","").trim());

            for (Object obj : listParent){
                if(obj.getClass() == CategoryParentItemList.class){
                    CategoryParentItemList p = (CategoryParentItemList)obj;
                    System.out.println("P-ItemName: "+ p.subCategoryName);
                }
            }

            CategoryItemListAdapter adapter;adapter = new CategoryItemListAdapter(SlidingContentFragment.this.getActivity().getBaseContext(), listParent);
            exListCategory.setAdapter(adapter);
            adapter.notifyDataSetChanged();
    }


}

public ArrayList<CategoryParentItemList> fetchResponse(String result)
{
    ArrayList<CategoryParentItemList> listParent = new ArrayList<CategoryParentItemList>();
    if (!result.equals(""))
    {
        try
        {
            JSONObject jsono = new JSONObject(result);
            JSONArray jarray = jsono.getJSONArray("SBL");

            CategoryParentItemList parent = null;

            for (int i = 0; i < jarray.length(); i++)
            {
                ArrayList<CategoryChildListItem> childrens = new ArrayList<CategoryChildListItem>();
                childrens.clear();
                CategoryChildListItem child;

                JSONObject object = jarray.getJSONObject(i);
                System.out.println("SCI: " + object.getInt("SubCategoryID"));
                System.out.println("SCN: " + object.getString("SubCategoryName"));

                JSONArray subItemArray = object.getJSONArray("SubCategoryItemList");

                if (subItemArray.length() > 0)
                {
                    for (int j = 0; j < subItemArray.length(); j++)
                    {
                        JSONObject subItemObject = subItemArray.getJSONObject(j);
                        String strItemName = subItemObject.getString("ItemName");
                        String strDefaultPrice = subItemObject.getString("DefaultPrice");

                        child = new CategoryChildListItem(strItemName, strDefaultPrice);
                        childrens.add(child);

                        Log.i("strItemName", strItemName);
                        Log.i("strDefaultPrice", strDefaultPrice);
                    }
                    parent = new CategoryParentItemList(object.getString("SubCategoryName"),childrens);
                    listParent.add(parent);
                }

            }

            //CategoryItemListAdapter adapter = new CategoryItemListAdapter(this, listParent, listChild);
            //exListCategory.setAdapter(adapter);

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

CategoeyItemListAdapter

 public class CategoryItemListAdapter extends BaseExpandableListAdapter
{

    private Context context;
    private ArrayList<CategoryParentItemList> parentItemLists;

    static class ViewHolderGroup
    {
        TextView lblSubCategoryName;
    }

    static class ViewHolderChild
    {
        TextView lblItemName;
        TextView lblDefualtPrice;
    }

    public CategoryItemListAdapter(Context context, ArrayList<CategoryParentItemList> listParent)
    {
        this.context = context;
        this.parentItemLists = listParent;
    }

    @Override
    public int getGroupCount()
    {

        return parentItemLists.size();
    }

    @Override
    public int getChildrenCount(int groupPosition)
    {

        return parentItemLists.get(groupPosition).childList.size();
    }

    @Override
    public Object getGroup(int groupPosition)
    {

        return parentItemLists.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition)
    {

        return parentItemLists.get(groupPosition).childList.get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition)
    {

        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition)
    {

        return childPosition;
    }

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

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
    {
        CategoryParentItemList parentItem = (CategoryParentItemList)parentItemLists.get(groupPosition);
        ViewHolderGroup holderGroup = null;
        if (convertView == null)
        {
            LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.group_header, null);
            holderGroup = new ViewHolderGroup();
            holderGroup.lblSubCategoryName = (TextView) convertView.findViewById(R.id.tvItemName);

        }
        else
        {
            holderGroup = (ViewHolderGroup) convertView.getTag();
        }

        holderGroup.lblSubCategoryName.setText(parentItem.getSubCategoryName());
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
    {
        CategoryParentItemList parentItem = (CategoryParentItemList)parentItemLists.get(groupPosition);
        CategoryChildListItem childItem = (CategoryChildListItem) parentItem.getChildList().get(childPosition);

        ViewHolderChild holder = null;

        if (convertView == null)
        {
            LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.child_row, null);
            holder = new ViewHolderChild();
            holder.lblItemName = (TextView) convertView.findViewById(R.id.tvSubItemName);
            holder.lblDefualtPrice = (TextView) convertView.findViewById(R.id.tvrRupees);
        }

        else
        {
            holder = (ViewHolderChild) convertView.getTag();
        }

        holder.lblItemName.setText(childItem.getSubItemName());
        holder.lblDefualtPrice.setText(childItem.getDefaultPrice());
        return convertView;
    }

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

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

//可扩展listview的组和子数据的POJO类

public class CategoryParentItemList {


    private String subCategoryName;

    public CategoryParentItemList(String subCategoryName){
        this.subCategoryName = subCategoryName;
    }

    public String getSubCategoryName() {
        return subCategoryName;
    }

    public void setSubCategoryName(String subCategoryName) {
        this.subCategoryName = subCategoryName;
    }
}



public class CategoryChildListItem {

    private String subItemName;
    private String defaultPrice;

    public CategoryChildListItem(String subItemName, String defaultPrice) {
        this.subItemName = subItemName;
        this.defaultPrice = defaultPrice;
    }

    public String getSubItemName() {
        return subItemName;
    }

    public void setSubItemName(String subItemName) {
        this.subItemName = subItemName;
    }

    public String getDefaultPrice() {
        return defaultPrice;
    }

    public void setDefaultPrice(String defaultPrice) {
        this.defaultPrice = defaultPrice;
    }


}

//现在上面的代码不是任何获取错误但是在页面的viewpager中,一些页面不显示内容,有时显示意味着它不持久,如果有任何想法请发布

1 个答案:

答案 0 :(得分:0)

Fisrt更改您的POJO classess如下:

public class CategoryParentItemList {

private String subCategoryName;
private int subCategoryID;
ArrayList<CategoryChildListItem> childList=new ArrayList<CategoryChildListItem>();

public CategoryParentItemList(String subCategoryName){
    this.subCategoryName = subCategoryName;
}

public String getSubCategoryName() {
    return subCategoryName;
}

public void setSubCategoryName(String subCategoryName) {
    this.subCategoryName = subCategoryName;
}

}

和您的子项目如下:

public class CategoryChildListItem {

private String subItemName;
private String defaultPrice;

public CategoryChildListItem(String subItemName, String defaultPrice) {
    this.subItemName = subItemName;
    this.defaultPrice = defaultPrice;
}

public String getSubItemName() {
    return subItemName;
}

public void setSubItemName(String subItemName) {
    this.subItemName = subItemName;
}

public String getDefaultPrice() {
    return defaultPrice;
}

public void setDefaultPrice(String defaultPrice) {
    this.defaultPrice = defaultPrice;
}

}

更改fetchResponse方法,如下所示:

private ArrayList<CategoryParentItemList> fetchResponse(String result)
    {
        ArrayList<CategoryParentItemList> listParent = new ArrayList<HomeAct.CategoryParentItemList>();
        if (!result.equals(""))
        {
            try
            {
                JSONObject jsono = new JSONObject(result);
                JSONArray jarray = jsono.getJSONArray("SBL");
                CategoryParentItemList parent = null; //new
                CategoryChildListItem child = null; //new
                for (int i = 0; i < jarray.length(); i++)
                {
                    JSONObject object = jarray.getJSONObject(i);

                    //Categories category = new Categories();
                    parent = new CategoryParentItemList(object.getString("SubCategoryName"));
                    parent.subCategoryID = object.getInt("SubCategoryID");
                    parent.subCategoryName = object.getString("SubCategoryName");

                    System.out.println("SCI: " + object.getString("SubCategoryID"));
                    System.out.println("SCN: " + object.getString("SubCategoryName"));

                    //category.setSubCatName(object.getString("SubCategoryName"));

                    JSONArray subItemArray = object.getJSONArray("SubCategoryItemList");

                    if (subItemArray.length() > 0)
                    {
                        parent.childList=new ArrayList<HomeAct.CategoryChildListItem>();
                        for (int j = 0; j < subItemArray.length(); j++)
                        {
                            JSONObject subItemObject = subItemArray.getJSONObject(j);
                            String strItemName = subItemObject.getString("ItemName");
                            String strDefaultPrice = subItemObject.getString("DefaultPrice");

                            child = new CategoryChildListItem(strItemName, strDefaultPrice);
                            parent.childList.add(child);

                            Log.i("strItemName", strItemName);
                            Log.i("strDefaultPrice", strDefaultPrice);
                        }

                    }
                    listParent.add(parent);
                }

                //CategoryItemListAdapter adapter = new CategoryItemListAdapter(this, listParent, listChild);
                //exListCategory.setAdapter(adapter);

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

更改onPostExecute()

@Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        System.out.println("Result: "+result);
        ArrayList<CategoryParentItemList> listParent = fetchResponse(result.replace("\n","").trim());
        CategoryItemListAdapter adapter = new CategoryItemListAdapter(getActivity(), listParent);
            exListCategory.setAdapter(adapter);
    }

同样更改你的适配器如下:

public class CategoryItemListAdapter extends BaseExpandableListAdapter
{

    private Context context;
    private ArrayList<CategoryParentItemList> parentItemLists;

    class ViewHolderGroup
    {
        TextView lblSubCategoryName;
    }

    class ViewHolderChild
    {
        TextView lblItemName;
        TextView lblDefualtPrice;
    }

    public CategoryItemListAdapter(Context context, ArrayList<CategoryParentItemList> listParent)
    {
        this.context = context;
        this.parentItemLists = listParent;
    }

    @Override
    public int getGroupCount()
    {

        return parentItemLists.size();
    }

    @Override
    public int getChildrenCount(int groupPosition)
    {

        return parentItemLists.get(groupPosition).childList.size();
    }

    @Override
    public Object getGroup(int groupPosition)
    {

        return parentItemLists.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition)
    {

        return parentItemLists.get(groupPosition).childList.get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition)
    {

        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition)
    {

        return childPosition;
    }

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

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
    {
        CategoryParentItemList parentItem = (CategoryParentItemList) getGroup(groupPosition);
        ViewHolderGroup holder = null;
        if (convertView == null)
        {
            LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.group_header, null);
            holder = new ViewHolderGroup();
            holder.lblSubCategoryName = (TextView) convertView.findViewById(R.id.tvSubItemName);
        }
        else
        {
            holder = (ViewHolderGroup) convertView.getTag();
        }

        holder.lblSubCategoryName.setText(parentItem.getSubCategoryName());
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
    {
        CategoryChildListItem childItem = (CategoryChildListItem) getChild(groupPosition, childPosition);
        ViewHolderChild holder = null;

        if (convertView == null)
        {
            LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.child_row, null);
            holder = new ViewHolderChild();
            holder.lblItemName = (TextView) convertView.findViewById(R.id.tvItemName);
            holder.lblDefualtPrice = (TextView) convertView.findViewById(R.id.tvrRupees);
        }

        else
        {
            holder = (ViewHolderChild) convertView.getTag();
        }

        holder.lblItemName.setText(childItem.getSubItemName());
        holder.lblDefualtPrice.setText(childItem.getDefaultPrice());
        return convertView;
    }

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

}