0

I have no idea what I'm screwing up here. Getting a null pointer exception seemingly on my array of Strings.

This is the method I'm calling in my main Activity:

public void initializeLocalDealer() {
  String[] cars = new String[]{"Ford", "Chevy", "Chrysler", "Honda"}; 
    Dealer dealer = new Dealer();
    Dealer.setCars(cars);
}

Here's the class object I'm trying to populate.

public class Dealer {

    public String name;
    public Car[] car;

    public Dealer() { }

    public void setCars(String[] cars) {
        for(int i = 0; i < cars.length; i++) {
            car[i].name = cars[i];
        }
    }
}

What super obvious thing am I missing here?

Rajat Jain
  • 1,339
  • 2
  • 16
  • 29
Matt
  • 51
  • 5
  • 4
    you need to initialize car array – Venki WAR Jun 09 '18 at 03:47
  • You might want to make your `setCars` method `static` because you call it like it is a `static` method. – 0xCursor Jun 09 '18 at 03:55
  • you create an instance of dealer, but again using Class name not instance name, use created instance.... check carefully..... Dealer dealer = new Dealer(); dealer.setCars(cars); – Amir Dora. Jun 09 '18 at 04:58

1 Answers1

1
Dealer dealer = new Dealer();
    dealer.setCars(cars); 

Modify Dealer.setCars(cars); to dealer.setCars(cars);

public class Dealer {

    public String name;
    public Car[] car;

    public Dealer() {

    }

    public void setCars(String[] cars) {
        -->car = new Car[cars.length];
        for(int i = 0; i < cars.length; i++) {
            car[i]= new Car(cars[i]);;

        }
    }


    }

add Constructor in your Car class

public Car(String name) {
    name =this.name;
}
Venki WAR
  • 1,997
  • 4
  • 25
  • 38
  • Still doesn't work. So if it definitely looks like I'm populating and passing my string in the calling method, maybe it's an problem with how I'm using Classes and Objects. So working from an innermost class out... I have Class1 which has String name; and Float value. I have the Cars Class which has String name and an array of Object1; I then have the Dealer Class which has a String name and an array of Cars. I thought if I made the "Dealer dealer = new Dealer(); that created an instance of everything enclosed in a Dealer object. Do I have to create a new object1 and where is it done? – Matt Jun 09 '18 at 04:25
  • few min I will try in my IDE – Venki WAR Jun 09 '18 at 04:55
  • I guess this is my confusion, I've never tried to embed my own objects in other objects using arrays. So let's say there's Class1 which has two members, one of which is the reference String Class. Class2 has an array of Object1. Class3 has an array of Object2. When I call Class3 class3 = new Class3() does this instantiate everything? What's the proper way to do this? Someone marked this as a duplicate question, but I looked at the answer and it doesn't clearly address how this is done. Thanks for the help. – Matt Jun 09 '18 at 05:18