带有JSON数据的ExpandableListView

时间:2017-06-23 23:53:54

标签: android json expandablelistview

我正在尝试为联赛冠军展示一个常备桌组。

我有3组:A组,B组,C组。

Foreach Group我有4支球队:Team1,Team2,Team3,Team4,他们的得分和比赛次数。

我已将数据作为JSON获取并成功将ArrayList中的数据传递给ExpandableListView适配器。

我在groupview方法上夸大了父行布局,因此它显示GROUP A,GROUP B,GROUP C,如下所示:

enter image description here

现在在团体新闻中我想要给这个自定义布局充气,这个布局显示了4支球队的身份,球队名称,比赛数,得分数:

enter image description here

这是我的模特课:

public class Standings_data {

    String id;
    String groupid;
    String team;

    public String getTeam() {
        return team;
    }

    public void setTeam(String team) {
        this.team = team;
    }

    public String getGroupid() {
        return groupid;
    }

    public void setGroupid(String groupid) {
        this.groupid = groupid;
    }

    String p;
    String pts;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }



    public String getP() {
        return p;
    }

    public void setP(String p) {
        this.p = p;
    }

    public String getPts() {
        return pts;
    }

    public void setPts(String pts) {
        this.pts = pts;
    }
}

我的片段类:

public class StandingFragment extends Fragment implements ConnectivityReceiver.ConnectivityReceiverListener,
        SwipeRefreshLayout.OnRefreshListener{
    public CoordinatorLayout coordinatorLayout;
    public boolean isConnected;
    public static final String NA = "NA";
    public RecyclerView recycler_post;
    public PostAdapter7 adapter;
    public ProgressDialog progressDialog;
    ArrayList<Standings_data> post_array = new ArrayList<>();
    public SwipeRefreshLayout swipeRefreshLayout;
    InterstitialAd mInterstitialAd;
    private InterstitialAd interstitial;
    public ExpandableListView elv;


    @Override
    public void onPrepareOptionsMenu(Menu menu) {

        super.onPrepareOptionsMenu(menu);
    }


    public StandingFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        checkConnectivity();

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v=inflater.inflate(R.layout.fragment_standing,null);

        // toolbar = (Toolbar) v.findViewById(R.id.toolbar_viewpager);
        // searchToolbar = (Toolbar) v.findViewById(R.id.toolbar_search);
        coordinatorLayout = (CoordinatorLayout) v.findViewById(R.id.coordinatorLayout);
        elv = (ExpandableListView)v.findViewById(R.id.elv);
        elv.setOnGroupExpandListener(onGroupExpandListenser);

        swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorGreen,R.color.black,R.color.colorRed);


        try {
            getData();
        } catch (Exception e) {
            e.printStackTrace();
        }


        return v;
    }
    ExpandableListView.OnGroupExpandListener onGroupExpandListenser = new ExpandableListView.OnGroupExpandListener() {
        int previousGroup =-1;
        @Override
        public void onGroupExpand(int groupPosition) {
            if(groupPosition!= previousGroup)
                elv.collapseGroup(previousGroup);
            previousGroup = groupPosition;
        }
    };



    public void getData() throws Exception {
        if (checkConnectivity()){
            try {
                swipeRefreshLayout.setRefreshing(true);
                getAllPosts();
            } catch (Exception e) {
                e.printStackTrace();

            }
        }else {
            swipeRefreshLayout.setRefreshing(false);

            // getAllPosts();
            showSnack();

        }
    }

    public boolean checkConnectivity() {
        return ConnectivityReceiver.isConnected();
    }

    public void showSnack() {

        Snackbar.make(coordinatorLayout, getString(R.string.no_internet_connected), Snackbar.LENGTH_INDEFINITE)
                .setAction(getString(R.string.settings), new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                    }
                }).setActionTextColor(Color.RED)
                .show();
    }
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_main, menu);


        super.onCreateOptionsMenu(menu,inflater);
    }


    @Override
    public void onResume() {
        super.onResume();
        // Toast.makeText(getContext(),"u have resumed the app",Toast.LENGTH_SHORT).show();
        AppController.getInstance().setConnectivityReceiver(this);
    }


    @Override
    public void onRefresh() {
        try {
            //  Toast.makeText(getContext(),"u have refreshed the app",Toast.LENGTH_SHORT).show();

            //when u swipe the app..the getdata method is invoked !
            getData();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @Override
    public void onPause() {
        super.onPause();
        // Toast.makeText(getContext(),"u have paused the app",Toast.LENGTH_SHORT).show();
    }



    @Override
    public void onNetworkChange(boolean inConnected) {
        this.isConnected = inConnected;
        // Toast.makeText(getContext(),"the app network have been changed",Toast.LENGTH_SHORT).show();

    }
    public void getAllPosts() throws Exception{
        String TAG = "POSTS_STANDINGS";
        String url = Constants.STANDINGS_URL;
        StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("response_standings", response);
                parseJson(response);
                progressDialog.dismiss();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                try {

                    progressDialog.dismiss();
                    swipeRefreshLayout.setRefreshing(false);
                    Log.e("error", "" +error.getMessage());
                }catch (NullPointerException e)
                {
                    swipeRefreshLayout.setRefreshing(false);
                    e.printStackTrace();
                }


            }
        });


        AppController.getInstance().addToRequestQueue(jsonObjectRequest, TAG);
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("الرجاء الانتظار..");
        progressDialog.show();
    }
    public void parseJson(String response){

        try {

            JSONArray array = new JSONArray(response);
            JSONObject jsonObject =null;
            post_array.clear();
            Standings_data p;
            for(int i=0 ; i<array.length() ; i++)
            {
                jsonObject=array.getJSONObject(i);

                String id_team=jsonObject.getString("id_team");
                String groupid= jsonObject.getString("name");
                String played=jsonObject.getString("played");
                String points=jsonObject.getString("points");

                p = new Standings_data();
                p.setId(id_team);
                p.setGroupid(groupid);
                p.setP(played);
                p.setPts(points);


                post_array.add(p);
                //realmHelper.save(p);
            }


        }
        catch (JSONException e) {
            swipeRefreshLayout.setRefreshing(false);
            e.printStackTrace();
            //Log.d("error", e.getMessage());
        }
        adapter = new PostAdapter7(getContext(),post_array );
        elv.setAdapter(adapter);
        swipeRefreshLayout.setRefreshing(false);

    }





}

我的适配器类:

public class PostAdapter7 extends BaseExpandableListAdapter{

    public Context mContext;

    public ArrayList<Standings_data> filtered_items = new ArrayList<>();


    //   ItemFilter mFilters = new ItemFilter();

    public PostAdapter7(Context mContext, ArrayList<Standings_data> postList) {
        this.mContext = mContext;
       this.filtered_items = postList;
    }
    @Override
    public int getGroupCount() {
        return filtered_items.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return 0;
        // not sure about the return value
    }

    @Override
    public Object getGroup(int groupPosition) {
        return null;
        // not sure about the return value

    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return null;
        // not sure about the return value
    }

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

    @Override
    public long getChildId(int i, int i2) {
        return 0;
    }

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

    @Override
    public View getGroupView(int i, boolean isExpanded, View view, ViewGroup parent) {
        final Standings_data post = filtered_items.get(i);
        if(view ==null)
        {
            LayoutInflater inflater =(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.parent_row,null);
        }
        TextView groupID = (TextView)view.findViewById(R.id.txtgroupid);
        groupID.setText(post.getGroupid());
        return view;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {

         // i have no idea what to do here so the four team are displayed from arraylist for each group

        return view;    }

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




}

如何显示foreach组(A,B,C,D)与包含数据的arraylist相对应的团队?

为了让我更清楚,我正在努力做到这一点:

enter image description here

更新:这是我的json回复

[{“0”:“1”,“id_team”:“1”,“1”:“TEAM 1”,“name”:“TEAM 1”,“2”:“3”,“已播放” :“3”,“3”:“9”,“points”:“9”},{“0”:“2”,“id_team”:“2”,“1”:“TEAM 2”,“name” “:”TEAM 2“,”2“:”3“,”play“:”3“,”3“:”1“,”points“:”1“},{”0“:”3“,” id_team “:” 3" , “1”: “TEAM3”, “名称”: “TEAM3”, “2”: “2”, “播放”: “2”, “3”: “6”, “点” : “6”}]

这是一个简单的测试

1 个答案:

答案 0 :(得分:1)

据我了解,您为主要群体(A组,B组,C组)获取儿童数据。

因此您的 post_array 用于保存团队数据,因此每个群组的子团队都有 post_array

您必须为您的群组创建一个 arrayList (A组,B组,C组)

您的孩子的

HashMap (每个小组的小组)哈希地图为您提供 post_array

示例:

把它放在onCreate

的顶端
List<String> listDataGroup = new ArrayList<String>();
HashMap<String, ArrayList<Standings_data>> listDataTeams = new HashMap<String, ArrayList<Standings_data>>();

然后在您的 parseJson()方法中将静态组添加到组列表中并在hashMap上填充您的团队

// Adding groups data
listDataGroup.add("Group A");
listDataGroup.add("Group B");
listDataGroup.add("Group C");

在您的for循环

之后向 post_array 添加数据之后
//adding childs data (Teams) like this
listDataTeams.put(listDataGroup.get(0), post_array); // Group, Child data(Teams)
listDataTeams.put(listDataGroup.get(1), post_array);
listDataTeams.put(listDataGroup.get(2), post_array);

请注意,之前的代码将为所有组添加相同的团队

然后将(listDataGroup,listDataTeams)传递给可扩展列表适配器,而不是传递 post_array

并在您的适配器上进行此操作

     public class PostAdapter7 extends BaseExpandableListAdapter{

            public Context mContext;
            List<String> listDataGroup ;
            HashMap<String, ArrayList<Standings_data>> listDataTeams;
            //   ItemFilter mFilters = new ItemFilter();

                public PostAdapter7(Context mContext, List<String> listDataGroup , HashMap<String, ArrayList<Standings_data>> listDataTeams) {
                    this.mContext = mContext;
                   this.listDataGroup = listDataGroup;
                   this.listDataTeams = listDataTeams;
                }
                @Override
                public int getGroupCount() {
                    return listDataGroup.size();
                }

                @Override
                public int getChildrenCount(int groupPosition) {
                    return this.listDataTeams.get(this.listDataGroup.get(groupPosition)).size();
                }

                @Override
                public Object getGroup(int groupPosition) {
                    return listDataGroup.get(groupPosition);
                }

                @Override
                public Object getChild(int groupPosition, int childPosition) {
                    return this.listDataTeams.get(this.listDataGroup.get(groupPosition)).get();
                }

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

                @Override
                public long getChildId(int i, int i2) {
                    return i2;
                }

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

                @Override
                public View getGroupView(int i, boolean isExpanded, View view, ViewGroup parent) {


        // this is for inflate Groups view and display data for it from listDataGroup array list 

                    if(view ==null)
                    {
                        LayoutInflater inflater =(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        view = inflater.inflate(R.layout.parent_row,null);
                    }


                    //here display your data for each Group

                    return view;
                }

                @Override
                public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) {

        // this is for inflate childs (Team view replace child_row with yours) and display data for it from listDataTeams HashMap 

        if(view ==null)
                    {
                        LayoutInflater inflater =(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        view = inflater.inflate(R.layout.child_row,null);
                    }

             //here get your data for each team and set it to your textview
             final Standings_data teamData = (Standings_data)getChild(groupPosition,childPosition);

              //and then in your tv display data
              yourTextView.setText(teamData.getGroupid());
         return view;
         }

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

            } 

我希望你明白这会......如果有问题请告诉我

如果你想要一个好的教程,可以使用ExpandableListViw 试试这个Tutorial

<强>更新

您可以使用此

对您的团队列表进行排序
    Collections.sort(post_array, new Comparator<Standings_data>(){
        public int compare(Standings_data s1, Standings_data s2) {
            return s1.getpts().compareToIgnoreCase(s2.getPts());
        }
    });

   Collections.reverse(post_array);

在将 post_array 添加到 listDataTeams 哈希映射

之前放置此代码