简体   繁体   中英

java.lang.NullPointerException when initialize array

I want to initialize and array to my pTotalPrice variable to hold the total price of the product * quantity. I got the error. I did that because the the tablelayout is dynamically created. I need to hold the value total price of each product, hence the final price shows the correct value if I deleted one of the product.

the error java.lang.NullPointerException is at pTotalPrice[i] = pPrice * pQuantity;

public class ScreenSecondFragment extends Fragment {

public ScreenSecondFragment(){}
public double pFinalPrice;
public double[] pTotalPrice;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_secondscreen, container, false);
    TextView showCartContent    = (TextView)rootView.findViewById(R.id.showCart);
    final Button thirdBtn       = (Button) rootView.findViewById(R.id.third);

    //Get Global Controller Class obiect (see application tag in AndroidManifest.xml)
    final Controller aController = (Controller) getActivity().getApplicationContext();

    // Get Cart Size
    final int cartSize = aController.getCart().getCartSize();

    /******** Dynamically create view elements - Start **********/

    TableLayout ll = (TableLayout) rootView.findViewById(R.id.displayTable);
    ll.setStretchAllColumns(true);
    ll.setShrinkAllColumns(true);

    TableLayout.LayoutParams params = new TableLayout.LayoutParams();
    params.setMargins(1, 1, 1, 1);

    TableRow.LayoutParams param = new TableRow.LayoutParams();
    param.span = 3;

    /****** Title header ******/
    TableRow rowProdLabels = new TableRow(this.getActivity());
    rowProdLabels.setBackgroundColor(android.graphics.Color.BLUE);

    // Product column
    TextView prodLabel = new TextView(this.getActivity());
    prodLabel.setText("PRODUCT");
    prodLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
    prodLabel.setTextSize(17);
    prodLabel.setTextColor(android.graphics.Color.WHITE);
    rowProdLabels.addView(prodLabel);

    // Price  column
    TextView priceLabel = new TextView(this.getActivity());
    priceLabel.setText("PRICE");
    priceLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
    priceLabel.setTextSize(17);
    priceLabel.setTextColor(android.graphics.Color.WHITE);
    rowProdLabels.addView(priceLabel);

    // Quantity column
    TextView quantityLabel = new TextView(this.getActivity());
    quantityLabel.setText("Quantity");
    quantityLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
    quantityLabel.setTextSize(17);
    quantityLabel.setTextColor(android.graphics.Color.WHITE);
    rowProdLabels.addView(quantityLabel);

    // Total column
    TextView totalLabel = new TextView(this.getActivity());
    totalLabel.setText("Total Price");
    totalLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
    totalLabel.setTextSize(17);
    totalLabel.setTextColor(android.graphics.Color.WHITE);
    rowProdLabels.addView(totalLabel);

    ll.addView(rowProdLabels, params);

    /****** Title header end ******/

    final TextView finalprice = new TextView(this.getActivity());

    if(cartSize >0)
    {
        for(int i=0;i<cartSize;i++)
        {   
            final int counter = i;
            // Get probuct data from product data arraylist
            String pName = aController.getProducts(i).getProductName();
            double pPrice   = aController.getProducts(i).getProductPrice();
            int pQuantity   = aController.getProducts(i).getProductQuantity();
            pTotalPrice[i] = pPrice * pQuantity;

            TableRow row= new TableRow(this.getActivity());
            row.setBackgroundColor(android.graphics.Color.WHITE);

            TextView product = new TextView(this.getActivity());
            product.setText(pName+"    ");
            product.setTextSize(15);
            //Add textView to LinearLayout
            row.addView(product);

            TextView price = new TextView(this.getActivity());
            price.setText("RM "+pPrice+"     ");
            price.setTextSize(15);
            //Add textView to LinearLayout
            row.addView(price);

            TextView quantity = new TextView(this.getActivity());
            quantity.setText(pQuantity+"     ");
            quantity.setTextSize(15);
            //Add textView to LinearLayout
            row.addView(quantity);

            TextView totalprice = new TextView(this.getActivity());
            totalprice.setText(String.format("RM %.2f",pTotalPrice[i]));
            totalprice.setTextSize(15);
            //Add textView to LinearLayout
            row.addView(totalprice);

            //Update final price
            pFinalPrice += pTotalPrice[i];

            final int index = i;
            Log.i("TAG", "index :" + index);
            // Get product instance for index

            final ModelProducts tempProductObiect = aController.getProducts(index);

            final Button btnRemove = new Button(this.getActivity());
            btnRemove.setId(i+1);
            btnRemove.setText("Delete");

            btnRemove.setOnClickListener(new OnClickListener()
            {
                @Override public void onClick(View v)
                {

                    if(aController.getCart().checkProductInCart(tempProductObiect))
                    {
                        // Product not Exist in cart so add product to
                        // Cart product arraylist
                        aController.getCart().removeProducts(tempProductObiect);

                        pFinalPrice -= pTotalPrice[counter];
                        finalprice.setText(String.format("RM %.2f",pFinalPrice));
                        Toast.makeText(getActivity().getApplicationContext(), "Now Cart size: "+aController.getCart().getCartSize(), 
                                Toast.LENGTH_LONG).show();
                    }
                    // row is your row, the parent of the clicked button
                    View row = (View) v.getParent();
                    // container contains all the rows, you could keep a variable somewhere else to the container which you can refer to here
                    ViewGroup container = ((ViewGroup)row.getParent());
                    // delete the row and invalidate your view so it gets redrawn
                    container.removeView(row);
                    container.invalidate();

                }
            });

            row.addView(btnRemove);

            ll.addView(row,i+1, params);            
        }
    }

    /****** Title footer ******/
    TableRow rowFinalLabels = new TableRow(this.getActivity());
    rowFinalLabels.setBackgroundColor(android.graphics.Color.BLUE);

    // Price  column
    TextView finalPriceLabel = new TextView(this.getActivity());
    finalPriceLabel.setText("FINAL PRICE");
    finalPriceLabel.setTypeface(Typeface.SERIF, Typeface.BOLD);
    finalPriceLabel.setTextSize(17);
    finalPriceLabel.setTextColor(android.graphics.Color.WHITE);
    rowFinalLabels.addView(finalPriceLabel, param);


    //final TextView finalprice = new TextView(this.getActivity());
    finalprice.setText(String.format("RM %.2f",pFinalPrice));
    finalprice.setTextColor(android.graphics.Color.WHITE);
    finalprice.setTypeface(Typeface.SERIF, Typeface.BOLD);
    finalprice.setTextSize(17);
    //Add textView to LinearLayout
    rowFinalLabels.addView(finalprice);

    ll.addView(rowFinalLabels);
    /****** Title footer end ******/

    thirdBtn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if(cartSize >0)
            {
                //Intent i = new Intent(getBaseContext(), ThirdScreen.class);
                //startActivity(i);
                FragmentTransaction mFragmentTransaction = getFragmentManager().beginTransaction();
                mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); 
                mFragmentTransaction.replace(R.id.frame_container, new BillingAddressFragment(), "Cart");
                mFragmentTransaction.commit();
            }
            else
                Toast.makeText(getActivity().getApplicationContext(), 
                        "Shopping cart is empty.", 
                        Toast.LENGTH_LONG).show();
        }
    }); 
    return rootView;
}
}

in java, you need initialize your array as following:

public double[] pTotalPrice= new double[10];

otherwise

public double[] pTotalPrice;

equals to

public double[] pTotalPrice = null;

您需要在将元素添加为之前初始化pTotalPrice

pTotalPrice=new double[cartSize];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM