0

I've been running into a nullPointerException while trying to add items to an arrayList. Below is the function that does that:

public void addToUtilityCardItems() {
        int[] utilitiesLogos = {R.drawable.kenya_power, R.drawable.nairobi_water, R.drawable.startimes, R.drawable.zuku};
        String[] utilitiesNames = {"Kenya Power", "Nairobi Water", "Startimes", "Zuku"};
        UtilitiesModel utilities = new UtilitiesModel();

        for (int i = 0; i < utilitiesNames.length; i++) {
            utilities.setUtilityLogo(utilitiesLogos[i]);
            utilities.setUtilityName(utilitiesNames[i]);
            utilityCardItems.add(utilities);
        }

    }

The error I get is:

java.lang.NullPointerException
            at com.sce.kbs.lient.FragmentTwo.addToUtilityCardItems(FragmentTwo.java:82)
            at com.sce.kbs.lient.FragmentTwo.onActivityCreated(FragmentTwo.java:56)

Kindly assist

8
  • My guess is that utilityCardItems is null Commented Jan 16, 2016 at 18:16
  • Are you instantiated utilityCardItems? Seems that it is not initialized and because of that you are getting NPE. Attach debugger on last line from your question. Commented Jan 16, 2016 at 18:19
  • Have you have initialised utilityCardItems?? Commented Jan 16, 2016 at 18:19
  • I would recommend you looking at the debugging functionality of your IDE. For example for android studio. Then look at the value being added in line 82. One of them seems to be null. Commented Jan 16, 2016 at 18:20
  • thanks, I modified this line private List<UtilitiesModel> utilityCardItems=new ArrayList<>();, but it only adds the last item after looping, i.e., 4 similar items of the last item in the arrays Commented Jan 16, 2016 at 18:25

1 Answer 1

1

If you want to add several utilities object:

public void addToUtilityCardItems() {
        int[] utilitiesLogos = {R.drawable.kenya_power, R.drawable.nairobi_water, R.drawable.startimes, R.drawable.zuku};
        String[] utilitiesNames = {"Kenya Power", "Nairobi Water", "Startimes", "Zuku"};


        for (int i = 0; i < utilitiesNames.length; i++) {
            UtilitiesModel utilities = new UtilitiesModel();
            utilities.setUtilityLogo(utilitiesLogos[i]);
            utilities.setUtilityName(utilitiesNames[i]);
            utilityCardItems.add(utilities);
        }

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

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.