0
    String quantityArray[] = GetStringArray(quantity);
    String foodItemArray[] = GetStringArray(fooditems);

this is to change from ArrayList to a String Array

    int n1 = fooditems.size();
    int n2 = quantity.size();

    for(int s = 0; s<n1;s++){

        totalFood[s] = quantityArray[s] + foodItemArray[s];
    }

I cannot make this totalFood[] function to work as it just keeps crashing my app

public static String[] GetStringArray(ArrayList<String> arr) {
    // declaration and initialise String Array
    String str[] = new String[arr.size()];
    // ArrayList to Array Conversion
    for (int j = 0; j < arr.size(); j++) {
        // Assign each value to String array
        str[j] = arr.get(j);
    }
    return str;
}

The error that pops up is (Attempt to write to null array)

2
  • Where are you allocating the totalFood array? Commented Jan 10, 2021 at 12:59
  • How did you initialize your totalFoods array? I can't see that in the code. Commented Jan 10, 2021 at 13:00

2 Answers 2

1

You need to make sure totalFood array is allocated.

Arrays are themselves Objects in Java.

For example:

totalFood = new String[n1];

This is because totalFood seems to be null according to the error you are seeing. You need to allocate some space (n1 references to be precise for the above example) for the Strings resulting from the concatenation to be stored at. You can take a look at the corresponding Java tutorial here.

Also make sure n1 is equal to n2 which should be equal also to the size of the totalFood array in order to not overrun any of them in your loop.

Finally, there are 2 handy Collection#toArray methods which will do what you are doing in your GetStringArray method. You can use it for example like so:

String quantityArray[] = quantity.toArray(new String[quantity.size()]);

Using the toArray method seems not to be related to the problem, but I just mention it for completeness.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeap for the totalFood was the issue so after i initialized i got it working thanks :)
0
public static String[] GetStringArray(ArrayList<String> arr) {
        String str[] = new String[arr.size()];
        for (int j = 0; j < arr.size(); j++) {
            str[j] = arr.get(j);
        }
        return Arrays.stream(str).filter(s -> s!=null).toArray(String[]::new);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.