Android IndexOutOfBoundsException索引无效,大小为0

时间:2016-02-29 02:58:28

标签: java android arrays json

我正在创建一个具有添加到购物车功能的应用。我遵循这个tutorial并且它工作正常,但是当我尝试在listview中添加产品的配置文件中的添加到购物车时,我得到一个错误, IndexOutOfBoundsException索引51无效,大小为0

ProductDetails.java

public class ProductDetails extends Fragment {

    static ConnectivityManager cm;
    AlertDialog dialog2;
    AlertDialog.Builder build;

    TextView txtproduct,
             txtprice,
             txtcategorytype,
             txtpieces,
             txtdescription;

    ImageView imgimage;

    Button btncart,
           btnview;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.product_details, container, false);

        final Controller ct = (Controller) getActivity().getApplicationContext();

        cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);// checking
        build = new AlertDialog.Builder(getActivity()); // connectivity

        // Create default options which will be used for every
        //  displayImage(...) call if no options will be passed to this method
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity())
                .defaultDisplayImageOptions(defaultOptions)
                .build();

        if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)// if connection is
                // there screen goes
                // to next screen
                // else shows
                // message
                .isConnectedOrConnecting()
                || cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                .isConnectedOrConnecting()) {
            Log.e("cm value",
                    ""
                            + cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                            .isConnectedOrConnecting());

            int teaProfileId = getArguments().getInt("teaProfileId");
            String teaProfileName = getArguments().getString("teaProfileName");
            Float teaProfilePrice = getArguments().getFloat("teaProfilePrice");
            String teaProfileImage = getArguments().getString("teaProfileImage");
            String teaProfileLabel = getArguments().getString("teaProfileLabel");
            int teaProfilePieces = getArguments().getInt("teaProfilePieces");
            String teaProfilePiecesType = getArguments().getString("teaProfilePiecesType");
            String teaProfileDescription = getArguments().getString("teaProfileDescription");


            try {
                JSONObject jsonObject1 = new JSONObject(String.valueOf(teaProfileId));
                JSONObject jsonObject2 = new JSONObject(teaProfileName);
                JSONObject jsonObject3 = new JSONObject(Float.toString(teaProfilePrice));
                JSONObject jsonObject4 = new JSONObject(teaProfileImage);
                JSONObject jsonObject5 = new JSONObject(teaProfileLabel);
                JSONObject jsonObject6 = new JSONObject(String.valueOf(teaProfilePieces));
                JSONObject jsonObject7 = new JSONObject(teaProfilePiecesType);
                JSONObject jsonObject8 = new JSONObject(teaProfileDescription);


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

            txtproduct = (TextView) rootView.findViewById(R.id.txtproduct);
            txtprice = (TextView) rootView.findViewById(R.id.txtprice);
            txtcategorytype = (TextView) rootView.findViewById(R.id.txtcategorytype);
            txtpieces = (TextView) rootView.findViewById(R.id.txtpieces);
            txtdescription = (TextView) rootView.findViewById(R.id.txtdescription);

            txtproduct.setText(teaProfileName);
            txtprice.setText(("PHP ") + String.format("%.2f", teaProfilePrice));
            txtcategorytype.setText(teaProfileLabel);
            txtpieces.setText((teaProfilePieces)+" "+(teaProfilePiecesType));
            txtdescription.setText(teaProfileDescription.replaceAll("<br />",""));
            imgimage = (ImageView)rootView.findViewById(R.id.imgimage);

            final ProgressBar progressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);

            ImageLoader.getInstance().displayImage(teaProfileImage, imgimage, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {
                    progressBar.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    progressBar.setVisibility(View.GONE);
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    progressBar.setVisibility(View.GONE);
                }

                @Override
                public void onLoadingCancelled(String imageUri, View view) {
                    progressBar.setVisibility(View.GONE);
                }
            });

        }

        else {

            build.setMessage("This application requires Internet connection. Would you connect to internet ?");
            build.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));

                }
            });
            build.setNegativeButton("No", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    getActivity().finish();
                }
            });
            dialog2 = build.create();
            dialog2.show();

        }


        btncart = (Button) rootView.findViewById(R.id.btncart);
        btncart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int teaProfileId = getArguments().getInt("teaProfileId");
                String teaProfileName = getArguments().getString("teaProfileName");
                Float teaProfilePrice = getArguments().getFloat("teaProfilePrice");
                String teaProfileImage = getArguments().getString("teaProfileImage");
                String teaProfileLabel = getArguments().getString("teaProfileLabel");
                int teaProfilePieces = getArguments().getInt("teaProfilePieces");
                String teaProfilePiecesType = getArguments().getString("teaProfilePiecesType");
                String teaProfileDescription = getArguments().getString("teaProfileDescription");

                Toast.makeText(getActivity(), teaProfileName+" was added to cart.", Toast.LENGTH_LONG).show();

                ProductModel productsObject = ct.getProducts(teaProfileId);

                    ct.getCart().setProducts(productsObject);

            }

        });

        btnview = (Button) rootView.findViewById(R.id.btnview);
        btnview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent in = new Intent(getActivity(),Screen1.class);
                startActivity(in);
            }
        });
        return rootView;
    }
}

Controller.java

public class Controller extends Application {

    private ArrayList<ProductModel> myproducts = new ArrayList<ProductModel>();

    private ModelCart myCart = new ModelCart();

    public ProductModel getProducts(int id){

        return myproducts.get(id);

    }

    public void setProducts(ProductModel products){

        myproducts.add(products);

    }

    public ModelCart getCart(){

        return myCart;

    }

}

ModelCart.java

public class ModelCart {

    private ArrayList<ProductModel> cartItems = new ArrayList<ProductModel>();

    public ProductModel getProducts(int position){

        return cartItems.get(position);


    }

    public void setProducts(ProductModel Products){

        cartItems.add(Products);

    }


    public int getCartsize(){

        return cartItems.size();

    }

    public boolean CheckProductInCart(ProductModel aproduct){


        return cartItems.contains(aproduct);


    }

}

这是logcat中的错误。

    java.lang.IndexOutOfBoundsException: Invalid index 51, size is 0
                                                         at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)

.Controller.getProducts(Controller.java:19)

.ProductDetails$4.onClick(ProductDetails.java:192)

这是第19行:return myproducts.get(id); 这是第192行:ProductModel productsObject = ct.getProducts(teaProfileId);

0 个答案:

没有答案