Android如何为可扩展listview初始化子数据和父数据

时间:2016-05-09 10:54:23

标签: android expandablelistview

向大家致以问候。我正在开发一个应用程序,我希望在其中实现动态ExpandableListView

ClientFunction.java

public class ClientFunction extends AppCompatActivity {
    String id, name, mo, city, pin, date, profmail;
    SessionManager session;
    ArrayList<HashMap<String, String>> arraylist;
    ListView orderlist;
    OrderListAdapter adapter;
    String amount, status;
    TextView amt;
    LinearLayout orderempty;
    Dialog dialog;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client_function);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        assert ab != null;
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setTitle("Orders");
        Intent i = getIntent();
        session = new SessionManager(this);
        HashMap<String, String> user = session.getUserDetails();
        profmail = user.get(SessionManager.KEY_EMAIL);
        orderempty = (LinearLayout) findViewById(R.id.layout_event_empty);
        orderempty.setVisibility(View.GONE);
        id = i.getStringExtra("clientid");
        name = i.getStringExtra("clientname");
        city = i.getStringExtra("address");
        mo = i.getStringExtra("mobileno");
        pin = i.getStringExtra("pincode");
        date = i.getStringExtra("date");
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();
        new HttpAsyncTask().execute(SessionManager.getAmateurPath() + "ViewOrder");

    }

    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            return POST(urls[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            orderlist = (ListView) findViewById(R.id.order_list);

            // Pass the results into ListViewAdapter.java
            adapter = new OrderListAdapter(ClientFunction.this, arraylist);
            // Set the adapter to the ListView
            orderlist.setAdapter(adapter);
        }
    }

    public String POST(String url) {
        InputStream inputStream;
        String result = "";
        try {
            arraylist = new ArrayList<HashMap<String, String>>();

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            String json = "";

            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("username", profmail);
            jsonObject.accumulate("cid", id);

            json = jsonObject.toString();
            Log.d("JSONStringSend", json);

            StringEntity se = new StringEntity(json);
            httpPost.setEntity(se);

            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse httpResponse = httpclient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();

            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                Log.d("JSONResponce", result);
                String add = "";
                JSONArray jsonArray = new JSONArray(result);
                for (int i = 0; i < jsonArray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    JSONObject mainjj = new JSONObject((String) jsonArray.get(i));
                    map.put("item", mainjj.getString("item"));
                    map.put("total", mainjj.getString("total"));
                    map.put("orderno", mainjj.getString("orderno"));
                    map.put("quantity", mainjj.getString("quantity"));
                    map.put("extrarate", mainjj.getString("extrarate"));
                    map.put("rate", mainjj.getString("rate"));
                    map.put("detail", mainjj.getString("detail"));
                    arraylist.add(map);
                    listDataHeader.add(mainjj.getString("item"));

                    List<String> mainjj.getString("item") = new ArrayList<String>();
                    mainjj.getString("item").add("Audi");
                    mainjj.getString("item").add("BMW");
                    mainjj.getString("item").add("Honda ");
                    mainjj.getString("item").add("POLO");

                }
                Log.d("ArrayList", arraylist.toString());
                Log.d("ArrayList123456789", "" + listDataHeader.toString());

            }


        } catch (Exception e) {

            Log.d("InputStream", e.getLocalizedMessage());
        }
        return result;
    }

    private String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;
        inputStream.close();
        return result;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_client_function, menu);
        //        MenuItem item = menu.findItem(R.id.add_order);
        //        SpannableStringBuilder builder = new SpannableStringBuilder("*    Login");
        //        // replace "*" with icon
        //        builder.setSpan(new ImageSpan(this, R.drawable.edit), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //        item.setTitle(builder);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case android.R.id.home: {
                finish();
                return true;
            }

            case R.id.profile: {
                Intent ii = new Intent(ClientFunction.this, ViewProfile.class);
                ii.putExtra("clientid", id);
                startActivity(ii);
                break;

            }
            case R.id.add_order: {
                Intent ii = new Intent(ClientFunction.this, AddOrder.class);
                ii.putExtra("clientid", id);
                ii.putExtra("clientname", name);
                ii.putExtra("date", date);
                ii.putExtra("pincode", pin);
                ii.putExtra("address", city);
                ii.putExtra("mobileno", mo);
                startActivity(ii);
                break;

            }
            adapter = new OrderListAdapter(ClientFunction.this, arraylist);
            case R.id.add_payment: {
                dialog = new Dialog(this);
                // dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(R.layout.addpayment);
                dialog.setTitle(Html.fromHtml("<font color='#FF7F27'>Add Payment</font>"));
                // dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.show();
                amt = (TextView) dialog.findViewById(R.id.amount);
                Button close = (Button) dialog.findViewById(R.id.save);
                close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        amount = amt.getText().toString();
                        if (amount.length() != 0) {
                            new HttpAsyncTask1().execute(SessionManager.getAmateurPath() + "AddProfessionalPayment");

                        } else {
                            amt.setError("Enter Amount");
                        }
                    }
                });

                break;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private class HttpAsyncTask1 extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            return POST1(urls[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            if (status.equalsIgnoreCase("success")) {
                amt.setHint("Enter Amount");
                dialog.dismiss();
                Toast.makeText(ClientFunction.this, "Amount Added Successfully", Toast.LENGTH_SHORT).show();
            } else
                Toast.makeText(ClientFunction.this, "Amount Added Failed", Toast.LENGTH_SHORT).show();
        }
    }

    public String POST1(String url) {
        InputStream inputStream;
        String result = "";
        try {
            arraylist = new ArrayList<HashMap<String, String>>();

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            String json = "";

            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("username", profmail);
            jsonObject.accumulate("clientid", id);
            jsonObject.accumulate("paymentrs", amount);


            json = jsonObject.toString();
            Log.d("JSONStringSend", json);

            StringEntity se = new StringEntity(json);
            httpPost.setEntity(se);

            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse httpResponse = httpclient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();

            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                Log.d("JSONResponce", result);
                String add = "";
                JSONObject mainjj = new JSONObject(result);
                status = mainjj.getString("status");

            }


        } catch (Exception e) {

            Log.d("InputStream", e.getLocalizedMessage());
        }
        return result;
    }

    public class OrderListAdapter extends BaseAdapter {
        Context context;
        LayoutInflater inflater;
        Button send1;

        ArrayList<HashMap<String, String>> data;
        int lastPosition = 0;
        private ColorGenerator mColorGenerator = ColorGenerator.MATERIAL;

        HashMap<String, String> resultp = new HashMap<String, String>();
        private DisplayImageOptions options;

        public OrderListAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
            this.context = context;
            data = arraylist;
        }

        @Override
        public int getCount() {
            if (data.size() == 0) {
                orderempty.setVisibility(View.VISIBLE);
                orderlist.setVisibility(View.GONE);

            }
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View itemView = inflater.inflate(R.layout.inflate_listoforder, parent, false);
            resultp = data.get(position);
            TextView iname = (TextView) itemView.findViewById(R.id.iname);
            TextView iid = (TextView) itemView.findViewById(R.id.iid);
            TextView iqty = (TextView) itemView.findViewById(R.id.iqty);
            TextView itotal = (TextView) itemView.findViewById(R.id.itotal);
            iname.setText("Item Name: " + resultp.get("item"));
            iid.setText("Item Id: " + resultp.get("orderno"));
            iqty.setText("ItemQuantity: " + resultp.get("quantity"));
            itotal.setText("ItemTotal: " + resultp.get("total"));

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    resultp = data.get(position);
                    Intent ii = new Intent(ClientFunction.this, ViewOrder.class);
                    ii.putExtra("item", resultp.get("item"));
                    ii.putExtra("clientid", id);
                    ii.putExtra("orderno", resultp.get("orderno"));
                    ii.putExtra("quantity", resultp.get("quantity"));
                    ii.putExtra("total", resultp.get("total"));
                    ii.putExtra("extrarate", resultp.get("extrarate"));
                    ii.putExtra("rate", resultp.get("rate"));
                    ii.putExtra("detail", resultp.get("detail"));
                    startActivity(ii);
                }
            });

            Animation animation = AnimationUtils.loadAnimation(context, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
            itemView.startAnimation(animation);
            lastPosition = position;
            return itemView;
        }
    }

}

我不知道如何在List<String> listDataHeaderHashMap<String, List<String>> listDataChild中添加数据。

我在listDataHeader成功添加了数据,但我不知道如何动态地将数据添加到listDataChild

我在listDataChild添加数据如下

  List<String> mainjj.getString("item") = new ArrayList<String>();
                mainjj.getString("item").add("Audi");
                mainjj.getString("item").add("BMW");
                mainjj.getString("item").add("Honda ");
                mainjj.getString("item").add("POLO");

但它不起作用。所以请帮我解决一下。这样我就可以继续编码了。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您的代码令人困惑,所以我在这里告诉您如何为ExpandableListView Header和Child添加数据(例如静态)。

//Function that return Map to add in adapter

public static Map<String, List<String>> getData() 
{
   Map<String, List<String>> expandableList = new TreeMap<>();

   List<String> Child1 = new ArrayList<String>();
   Child1.add("Child data......");

   List<String> Child2 = new ArrayList<String>();
   Child2.add("Child data......");

   List<String> Child3 = new ArrayList<String>();
   Child3.add("Child data........");


   expandableList.put("Header-1", Child1);
   expandableListDetail.put("Header-2",Child2);
   expandableListDetail.put("Header-3",Child3);
   expandableListDetail.put("Header-4",Child4);

   return expandableListDetail;
}

这里我只是添加自己的数据,但是对于动态行为,你必须使用循环将数据添加到“expandablList”&amp; “孩子”名单。