带复选框的动态列表视图问题?

时间:2016-02-29 13:12:25

标签: java android xml android-layout

我想在包含价格和文字的动态列表视图中添加复选框。当iam尝试添加复选框操作时,该列表正确显示,显示胎儿错误。

这是代码....请提前感谢帮我解决这个问题。

适配器类: -

    import android.app.Activity;
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.CheckBox;
    import android.widget.CheckedTextView;
    import android.widget.CompoundButton;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.util.ArrayList;

    class AdapterMenuList extends BaseAdapter {

            private Activity activity;
        ArrayList<AdapterMenuList> objects;
        boolean box;

            public AdapterMenuList(Activity act) {
                this.activity = act;


            }

            public int getCount() {
                // TODO Auto-generated method stub
                return ActivityMenuList.sub_service_id.size();
            }

            public Object getItem(int position) {
                // TODO Auto-generated method stub
                return position;
            }

            public long getItemId(int position) {
                // TODO Auto-generated method stub
                return position;
            }
        AdapterMenuList getAdapterMenuList(int position) {

            return ((AdapterMenuList) getItem(position));
        }
            public View getView(int position, View convertView, ViewGroup parent) {
                // TODO Auto-generated method stub
                ViewHolder holder;
                AdapterMenuList p = getAdapterMenuList(position);
                if(convertView == null){
                    LayoutInflater inflater = (LayoutInflater) activity
                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.menu_list_item, null);
                    holder = new ViewHolder();

                    convertView.setTag(holder);
                }else{
                    holder = (ViewHolder) convertView.getTag();
                }

                holder.txtText = (TextView) convertView.findViewById(R.id.txtText);
                holder.txtSubText = (TextView) convertView.findViewById(R.id.txtSubText);
                holder.ch = (CheckBox)convertView.findViewById(R.id.checkBox);
                holder.txtText.setText(ActivityMenuList.sub_service_name.get(position));
                holder.txtSubText.setText(ActivityMenuList.price.get(position)+" "+ ActivityMenuList.Currency);
                holder.ch.setTag(position);
                holder.ch.setChecked(p.box);
                holder.ch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        getAdapterMenuList((Integer) buttonView.getTag()).box = isChecked;

                    }
                });


                return convertView;
            }


        ArrayList<AdapterMenuList> getBox() {
            ArrayList<AdapterMenuList> box = new ArrayList<AdapterMenuList>();
            for (AdapterMenuList p : objects) {
                if (p.box)
                    box.add(p);
            }
            return box;
        }

            static class ViewHolder {
                TextView txtText;
                TextView txtSubText;
                CheckBox ch;

            }
        }

列出Activity.java: -

  public class   ActivityMenuList extends Activity {

        ListView listMenu;
        ProgressBar prgLoading;
        //TextView txtTitle;
        EditText edtKeyword;
        ImageButton btnSearch;
        TextView txtAlert;

        // declare static variable to store tax and currency symbol
        static double Tax;
        static String Currency;

        // declare adapter object to create custom menu list
        AdapterMenuList mla;

        // create arraylist variables to store data from server
        static ArrayList<Long> sub_service_id = new ArrayList<Long>();
        static ArrayList<String> sub_service_name = new ArrayList<String>();
        static ArrayList<Double> price = new ArrayList<Double>();


        String MenuAPI;
        String TaxCurrencyAPI;
        int IOConnect = 0;
        long service_id;
        String service_name;
        String Keyword;

        // create price format
        DecimalFormat formatData = new DecimalFormat("#.##");


        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.menu_list);

            ActionBar bar = getActionBar();
            bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
            bar.setTitle("Product");
            bar.setDisplayHomeAsUpEnabled(true);
            bar.setHomeButtonEnabled(true);
            prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
            listMenu = (ListView) findViewById(R.id.listMenu);
            edtKeyword = (EditText) findViewById(R.id.edtKeyword);
            btnSearch = (ImageButton) findViewById(R.id.btnSearch);
            txtAlert = (TextView) findViewById(R.id.txtAlert);

            // menu API url
            MenuAPI = Constant.MenuAPI+"?accesskey="+Constant.AccessKey+"&service_id=";
            // tax and currency API url
            TaxCurrencyAPI = Constant.TaxCurrencyAPI+"?accesskey="+Constant.AccessKey;

            // get category id and category name that sent from previous page
            Intent iGet = getIntent();
            service_id = iGet.getLongExtra("service_id",0);
            service_name = iGet.getStringExtra("service_name");
            MenuAPI += service_id;

            // set category name to textview
    //        txtTitle.setText(Category_name);

            mla = new AdapterMenuList(ActivityMenuList.this);

            // call asynctask class to request tax and currency data from server
            new getTaxCurrency().execute();

            // event listener to handle search button when clicked
            btnSearch.setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    // get keyword and send it to server
                    try {
                        Keyword = URLEncoder.encode(edtKeyword.getText().toString(), "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    MenuAPI += "&keyword="+Keyword;
                    IOConnect = 0;
                    listMenu.invalidateViews();
                    clearData();
                    new getDataTask().execute();
                }
            });

            // event listener to handle list when clicked
            listMenu.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                        long arg3) {
                    // TODO Auto-generated method stub
                    // go to menu detail page
                    String result = "Selected Product are :";

                    for (AdapterMenuList p : mla.getBox()) {
                        if (p.box){
                            result += "\n" + sub_service_name;

                        }
                    }
                    Toast.makeText(ActivityMenuList.this,  result+"Total Amount:=" + sub_service_name, Toast.LENGTH_LONG).show();
                }
            });       

        }

        @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_category, menu);


            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 R.id.cart:
                // refresh action
                Intent iMyOrder = new Intent(ActivityMenuList.this, ActivityMenuList.class);
                startActivity(iMyOrder);
                overridePendingTransition (R.anim.open_next, R.anim.close_next);
                return true;

            case R.id.refresh:
                IOConnect = 0;
                listMenu.invalidateViews();
                clearData();
                new getDataTask().execute();
                return true;            

            case android.R.id.home:
                // app icon in action bar clicked; go home
                this.finish();
                overridePendingTransition(R.anim.open_main, R.anim.close_next);
                return true;

            default:
                return super.onOptionsItemSelected(item);
            }
        }

        // asynctask class to handle parsing json in background
        public class getTaxCurrency extends AsyncTask<Void, Void, Void>{

            // show progressbar first
            getTaxCurrency(){
                if(!prgLoading.isShown()){
                    prgLoading.setVisibility(0);
                    txtAlert.setVisibility(8);
                }
            }

            @Override
            protected Void doInBackground(Void... arg0) {
                // TODO Auto-generated method stub
                // parse json data from server in background
                parseJSONDataTax();
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                // TODO Auto-generated method stub
                // when finish parsing, hide progressbar
                prgLoading.setVisibility(8);
                // if internet connection and data available request menu data from server
                // otherwise, show alert text
                if((Currency != null) && IOConnect == 0){
                    new getDataTask().execute();
                }else{
                    txtAlert.setVisibility(0);
                }
            }
        }

        // method to parse json data from server
        public void parseJSONDataTax(){
            try {
                // request data from tax and currency API
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
                HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
                HttpUriRequest request = new HttpGet(TaxCurrencyAPI);
                HttpResponse response = client.execute(request);
                InputStream atomInputStream = response.getEntity().getContent();

                BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));

                String line;
                String str = "";
                while ((line = in.readLine()) != null){
                    str += line;
                }


                // parse json data and store into tax and currency variables
                JSONObject json = new JSONObject(str);
                JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part

                JSONObject object_tax = data.getJSONObject(0); 
                JSONObject tax = object_tax.getJSONObject("tax_n_currency");

                Tax = Double.parseDouble(tax.getString("Value"));

                JSONObject object_currency = data.getJSONObject(1); 
                JSONObject currency = object_currency.getJSONObject("tax_n_currency");

                Currency = currency.getString("Value");


            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                IOConnect = 1;
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }

        // clear arraylist variables before used
        void clearData(){
            sub_service_id.clear();
            sub_service_name.clear();
            price.clear();

        }

        // asynctask class to handle parsing json in background
        public class getDataTask extends AsyncTask<Void, Void, Void>{

            // show progressbar first
            getDataTask(){
                if(!prgLoading.isShown()){
                    prgLoading.setVisibility(0);
                    txtAlert.setVisibility(8);
                }
            }

            @Override
            protected Void doInBackground(Void... arg0) {
                // TODO Auto-generated method stub
                // parse json data from server in background
                parseJSONData();
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                // TODO Auto-generated method stub
                // when finish parsing, hide progressbar
                prgLoading.setVisibility(8);

                // if data available show data on list
                // otherwise, show alert text
                if(sub_service_id.size() > 0){
                    listMenu.setVisibility(0);
                    listMenu.setAdapter(mla);
                }else{
                    txtAlert.setVisibility(0);
                }

            }
        }

        // method to parse json data from server
        public void parseJSONData(){

            clearData();

            try {
                // request data from menu API
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
                HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
                HttpUriRequest request = new HttpGet(MenuAPI);
                HttpResponse response = client.execute(request);
                InputStream atomInputStream = response.getEntity().getContent();

                BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));

                String line;
                String str = "";
                while ((line = in.readLine()) != null){
                    str += line;
                }

                // parse json data and store into arraylist variables
                JSONObject json = new JSONObject(str);
                JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part

                for (int i = 0; i < data.length(); i++) {
                    JSONObject object = data.getJSONObject(i); 

                    JSONObject menu = object.getJSONObject("Menu");

                    sub_service_id.add(Long.parseLong(menu.getString("sub_service_id")));
                    sub_service_name.add(menu.getString("sub_service_name"));
                    price.add(Double.valueOf(formatData.format(menu.getDouble("price"))));


                }


            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }


        @Override
        protected void onDestroy() {
            // TODO Auto-generated method stub
            //mla.imageLoader.clearCache();
            listMenu.setAdapter(null);
            super.onDestroy();
        }


        @Override
        public void onConfigurationChanged(final Configuration newConfig)
        {
            // Ignore orientation change to keep activity from restarting
            super.onConfigurationChanged(newConfig);
        }

        @Override
        public void onBackPressed() {
            // TODO Auto-generated method stub
            super.onBackPressed();
            finish();
            overridePendingTransition(R.anim.open_main, R.anim.close_next);
        }


    }

main.xml中: -

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#e7e7e7" >

        <LinearLayout
            android:id="@+id/lytSearch"
            android:layout_width="fill_parent"
            android:layout_height="45dp"
            android:background="@color/header"
            android:gravity="center_vertical"
            android:visibility="visible" >

            <EditText
                android:id="@+id/edtKeyword"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_marginLeft="5dp"
                android:layout_weight="1"
                android:background="@drawable/search_form"
                android:hint="@string/search"
                android:padding="7dp"
                android:textColor="@color/hint"
                android:textSize="14sp"
                android:inputType="text"
                android:singleLine="true" />

            <ImageButton
                android:id="@+id/btnSearch"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:background="@color/header"
                android:src="@drawable/ic_search" />

        </LinearLayout>

        <ListView
            android:visibility="gone"
            android:id="@+id/listMenu"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/lytSearch"
            android:divider="@null"
            android:padding="5dp" />

        <ProgressBar
            android:id="@+id/prgLoading"
            android:layout_height="wrap_content" 
            android:layout_width="wrap_content"
            android:layout_centerInParent="true" />
        <TextView 
            android:id="@+id/txtAlert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/not_found"
            android:textSize="14sp"
            android:layout_centerInParent="true"
            android:visibility="gone"/>

</RelativeLayout>

List_item.xml: -

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#e7e7e7"
    android:padding="5dp" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_top_style_1"
        android:orientation="vertical"
        android:padding="5dp" >



        <RelativeLayout
            android:id="@+id/lytText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp" >

            <TextView
                android:id="@+id/txtText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_toLeftOf="@+id/txtSubText"
                android:maxLines="2"
                android:text="aaa"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/txtSubText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:text="bbb" />

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="select"
                android:id="@+id/checkBox"
                android:layout_centerVertical="true"
                android:layout_centerHorizontal="true"
                android:checked="false" />

        </RelativeLayout>
    </LinearLayout>

</RelativeLayout>

错误消息: -

02-29 08:22:13.848 18814-18814/com.theredandblack.ecommerce E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.theredandblack.ecommerce, PID: 18814
                                                                              java.lang.ClassCastException: java.lang.Integer cannot be cast to com.theredandblack.ecommerce.AdapterMenuList
                                                                                  at com.theredandblack.ecommerce.AdapterMenuList.getAdapterMenuList(AdapterMenuList.java:45)
                                                                                  at com.theredandblack.ecommerce.AdapterMenuList.getView(AdapterMenuList.java:50)
                                                                                  at android.widget.AbsListView.obtainView(AbsListView.java:2255)
                                                                                  at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
                                                                                  at android.widget.ListView.onMeasure(ListView.java:1175)
                                                                                  at android.view.View.measure(View.java:16497)
                                                                                  at android.widget.RelativeLayout.measureChild(RelativeLayout.java:689)
                                                                                  at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:473)
                                                                                  at android.view.View.measure(View.java:16497)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
                                                                                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                                  at android.view.View.measure(View.java:16497)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
                                                                                  at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
                                                                                  at android.view.View.measure(View.java:16497)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
                                                                                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                                  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
                                                                                  at android.view.View.measure(View.java:16497)
                                                                                  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1912)
                                                                                  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1109)
                                                                                  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1291)
                                                                                  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
                                                                                  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
                                                                                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
                                                                                  at android.view.Choreographer.doCallbacks(Choreographer.java:574)
                                                                                  at android.view.Choreographer.doFrame(Choreographer.java:544)
                                                                                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
                                                                                  at android.os.Handler.handleCallback(Handler.java:733)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                  at android.os.Looper.loop(Looper.java:136)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                                                  at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                  at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                                                  at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

问题在于您的getAdapterMenuList(int position)方法。你正在返回((AdapterMenuList) getItem(position));,其中probablhy抛出一个ClassCastException,因为getItem返回一个你试图强制转换为AdapterMenuList的int