0

This code is very vital to my project. It refreshes items from a sql server that I have created. It does not load any of the items and gives me a Null Pointer Exception.

private void refreshItemsToInventoryList() {

    // Get the items that weren't marked as completed and add them in the
    // adapter

    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
        @Override
        protected Void doInBackground(Void... params) {

            try {
                final List<Item> results = refreshItemsFromInventoryTable();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mInventoryAdapter.clear();

                        for (Item item : results) {
                            mInventoryAdapter.add(item);
                        }
                    }
                });
            } catch (final Exception e){
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }
    };

    runAsyncTask(task);
}

/**
 * Refresh the list with the items in the Inventory Table
 */

@Nullable
private List<Item> refreshItemsFromInventoryTable() throws ExecutionException, InterruptedException {

    ResultSet rs;
    List<Item> inventoryItems = null;
    try {
        String query = "SELECT * FROM Inventory; ";
        Statement stmt = con.createStatement();
        rs = stmt.executeQuery(query);

        while (rs.next()){
            inventoryItems.add(new Item(rs.getString("ItemDescription")));
        }
    }
    catch (SQLException sql)
    {
        createAndShowDialog(sql.getMessage(), "Error");
    }

    return inventoryItems;
}

This code is to create and add items to a list, but it unfortunately gives me a Null Pointer Exception.

Darren
  • 29
  • 7

2 Answers2

0

Do you have records in the Inventory table? If no you will always have null as you are returning the initialized inventoryItems result

0

First things: does your inventory database table have rows? Did you open up your database connection properly?

Whenever I get a Null Pointer Exception, I find it really helpful to set a breakpoint right before the line that the logcat points to that is in error. You can then watch the variables and items, and see if they are being populated, or are null.

shagberg
  • 2,427
  • 1
  • 12
  • 23