Unable to split string to array and store to array object in Android Java

89 views Asked by At

Is there any way to splits a string into an array and loop it into an array class in android java? Below is my code but it cannot loop

Sample ScanResultProduct record ="P001,7,1,7,P002,8,2,16";

        String ScanResultProduct[];
        ScannedProductList[] ScannedProductList;

        ScanResultProduct = UserScanResulted.split(",");
        int Length = ScanResultProduct.length;
        int LengthResult = Length / 4;
        ScannedProductList[] ScanResultProductList = new ScannedProductList[LengthResult];


        for (int i = 0, index = 0; index < ScannedProductList.length; index++) {
            ScanResultProductList[index] = new ScannedProductList(ScanResultProduct[i], ScanResultProduct[i + 1], ScanResultProduct[i + 2], ScanResultProduct[i + 3]);
            i += 4;
        }

This is the ScanResultProductList class

public class ScannedProductList {
    public String ProductID;
    public String ProductPrice;
    public String ProductQuantity;
    public String ProductTotalPrice;

    public ScannedProductList(String productID, String productPrice, String productQuantity, String productTotalPrice) {
        ProductID = productID;
        ProductPrice = productPrice;
        ProductQuantity = productQuantity;
        ProductTotalPrice = productTotalPrice;
    }

    public String getProductID() {
        return ProductID;
    }

    public String getProductPrice() {
        return ProductPrice;
    }

    public String getProductQuantity() {
        return ProductQuantity;
    }

    public String getProductTotalPrice() {
        return ProductTotalPrice;
    }

    public String Display(){
        return ProductID + "," + ProductPrice + "," + ProductQuantity +","+ ProductTotalPrice;
    }

    public void setProductID(String productID) {
        ProductID = productID;
    }

    public void setProductPrice(String productPrice) {
        ProductPrice = productPrice;
    }

    public void setProductQuantity(String productQuantity) {
        ProductQuantity = productQuantity;
    }

    public void setProductTotalPrice(String productTotalPrice) {
        ProductTotalPrice = productTotalPrice;
    }
}

It unable to loop and the error message are

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.finalfypprojectapplication, PID: 14722 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.finalfypprojectapplication/com.example.finalfypprojectapplication.ConfirmPaymentActivity}: java.lang.NullPointerException: Attempt to get length of null array

1

There are 1 answers

0
Alek KT On BEST ANSWER

It's a NullPointerException. Before calling a split, you have to check if your String != nulll. After, be sure that your String[] is not null before calling the length method. After that, If i were you, when I have a String[], I will build my object in a For Loop by using your setters.