Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;
}
}
share|improve this question
    
you haven't initialized pTotalPrice anywhere. –  panini Apr 17 at 2:03

2 Answers 2

up vote 1 down vote accepted

You need to initialize pTotalPrice before adding elements as:

pTotalPrice=new double[cartSize];
share|improve this answer

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;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.