grantmcconnaughey
grantmcconnaughey

Reputation: 10689

Grails - Cannot invoke method getAt() on null object

I am getting an error when trying to append a book to a list of classes list of books. Any ideas as to why or what I could do to fix it?

        //For each book in a class...
        for (int k = 0; k < rows.size(); k++) {
            Book book = new Book()

            //Assign the values to a new book object
            book.id            = rows[k].getProperty("ISBN")
            book.title         = rows[k].getProperty("title")
            book.author        = rows[k].getProperty("author")
            book.required      = rows[k].getProperty("required_optional")
            book.purchaseType  = rows[k].getProperty("rental_purchase")
            //book.purchasePrice = rows[k].getProperty("purchase_price")
            //book.rentalPrice   = rows[k].getProperty("rental_fee")

            //Append the book to the books list object in the particular class
            classes[i].books[k + 1] << book
        }

Upvotes: 2

Views: 9588

Answers (4)

Aakarsh Gupta
Aakarsh Gupta

Reputation: 205

Instead of accessing by [] use getAt, then the ? Operator will work:

classes?.getAt(i)?.books?.getAt(k+1) << book

or

classes?.getAt(i)?.books[k+1] << book

Upvotes: 4

Eddard Stark
Eddard Stark

Reputation: 3595

I am not sure what 'classes' is, but if its a list containing 'Book' you can just do

classes << book

OR

classes.add(book)

Upvotes: 0

moskiteau
moskiteau

Reputation: 1102

rows.each { row ->
  Book book = new Book(...)
  classes[i].books << book
}

Upvotes: 2

moeTi
moeTi

Reputation: 3904

without the full code it's hard to know what happens. try this code, it will show you which value is null:

// first check if classes[i] is null, add error handling if it is
if (classes[i]!=null) {
    //For each book in a class...
    for (int k = 0; k < rows.size(); k++) {     
        def books = classes[i].books[k + 1]
        if (books!=null) {
            // you can set values directly here
            def row = rows[k]
            Book book = new Book(
                id: k.getProperty("ISBN"),
                title: k.getProperty("title")
                // ...
            )
            //Append the book to the books list object in the particular class
            books << book
        } else {
            println "books is null, do something clever"
        }
    }
} else {
    println "classes[i] is null, do something clever"
}

I didn't test it, and you can probably make it shorter with some groovy goodness. this is just to get you started

Upvotes: 0

Related Questions