title: Android: Null Pointer Exception Attempt to invoke virtual method on a null object reference
body: <p>I am a beginner working with Android studio. I have an assignment at hand where I am supposed to use the spinner control containing choices to fetch database records from a books.db such as records with highest and lowest values, record count etc.
  Below are my Main class and SQLHelper classes listing the details.
  I keep getting this Null Pointer Exception everytime I try to run the code. I have literally tried everything but nothing seems to work!</p>
  
  <p>Can someone please help?</p>
  
  <p><strong>Main Class</strong></p>
  
  <pre><code>    package com.example.amrapali.bookreviews;
  
      import android.content.DialogInterface;
      import android.os.Bundle;
      import android.support.v7.app.AppCompatActivity;
      import android.util.Log;
      import android.view.View;
      import android.widget.AdapterView;
      import android.view.View.OnClickListener;
      import android.widget.AdapterView.OnItemSelectedListener;
      import android.widget.ArrayAdapter;
      import android.widget.ListView;
      import android.widget.Spinner;
      import android.widget.Toast;
  
      import java.util.ArrayList;
      import java.util.Collections;
      import java.util.Comparator;
      import java.util.List;
      import java.util.Set;
  
  
      public class MainActivity extends AppCompatActivity implements OnClickListener, OnItemSelectedListener {
  
  
          SqlHelper db;
  
          boolean blnFlag=false;
  
          private String tag = "My Name Is:";
  
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              Log.i(tag, "Amrapali");
              super.onCreate(savedInstanceState);
              setContentView(R.layout.spinner);
              SqlHelper db = new SqlHelper(this);
  
              /** CRUD Operations **/
              // add Books
              //db.addBook(new Book("Professional Android 4 Application Development", "Reto Meier"));
              //db.addBook(new Book("Beginning Android 4 Application Development", "Wei-Meng Lee"));
              //db.addBook(new Book("Programming Android", "Wallace Jackson"));
              //db.addBook(new Book("Hello, Android", "Wallace Jackson"));
  
              // get all books
              List&lt;Book&gt; list = db.getAllBooks();
              ListView listContent = (ListView) findViewById(R.id.list);
              List&lt;Book&gt; books = new ArrayList&lt;Book&gt;();
              books=db.getAllBooks();
  
              //get data from the table by the ListAdapter
              //ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow,  books);
              //listContent.setAdapter(customAdapter);
              //Book updateBook = list.get(3);
  
              // Spinner element
              Spinner spinner;
  
              // Spinner    element
              spinner = (Spinner) findViewById(R.id.spinner1);
  
              // Spinner Drop down element items (some list you build)
              List&lt;String&gt; blist = new ArrayList&lt;String&gt;();
  
              blist.add(0,"Select Analytics...");
              blist.add(1,"Get Highest Rated Title(s)");
              blist.add(2,"Get Lowest Rated Title(s)");
              blist.add(3,"Get Record Count");
              blist.add(4,"Retrieve Title(s) with Android 4");
  
              // Creating adapter for spinner, pass your list into the constructor
              ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, blist);
  
              // Drop down layout style - list view with radio button
              adapter.setDropDownViewResource(R.layout.myspinner);
  
              // attaching data adapter to spinner
              spinner.setAdapter(adapter);
  
              // Spinner click listener
              spinner.setOnItemSelectedListener(this);
  
          }     //end  onCreate() method
  
          @Override
          public void onItemSelected(AdapterView&lt;?&gt; parentView, View selectedItemView, int position, long id)  {
              // TODO Auto-generated method stub
  
              if(blnFlag)   //spoof message from displaying initially
              {
                  if(position==1)
                  {
                      String condition = parentView.getItemAtPosition(position).toString();
                      Toast.makeText(this,"Highest Rating =  " + db.getHighestRating(condition), Toast.LENGTH_LONG).show();
  
                  }
                  //get query result for Highest rated title(s)
  
                  //display query result(s) in a Toast message
  
                  if(position==2) {
  
                      String condition = parentView.getItemAtPosition(position).toString();
                      Toast.makeText(this,"Lowest Rating =  " + db.getLowestRating(condition), Toast.LENGTH_LONG).show();
  
                      //get query result for Lowest rated title(s)
  
                      //display query result(s) in a Toast message
                  }
                  if(position==3)
                  {
                      String condition = parentView.getItemAtPosition(position).toString();
                      Toast.makeText(this,"Total Number of Records =  " + db.getCount(condition),
                              Toast.LENGTH_LONG).show();
  
                  }
              }
              blnFlag=true;
          }
  
          @Override
          public void onNothingSelected(AdapterView&lt;?&gt;   parentView)  {
              // TODO Auto-generated method stub
          }
  
  
          @Override
          public void onClick(View v) {
  
          }
          // update one book
          //int j = db.updateBook(updateBook,"Hello, Android","Ben Jackson");
  
          // delete one book
          //db.deleteBook(list.get(0));
  
          // get all books
          //db.getAllBooks();
  
          //Log.d("The book count is ", Integer.toString(db.getIds(updateBook)));
      }
  </code></pre>
  
  <p><strong>SQLHelper Class:</strong></p>
  
  <pre><code>    package com.example.amrapali.bookreviews; /**
       * Created by Amrapali on 4/3/2016.
       */
      import java.util.HashSet;
      import java.util.LinkedList;
      import java.util.List;
      import java.util.Set;
  
      import android.content.ContentValues;
      import android.content.Context;
      import android.database.Cursor;
      import android.database.sqlite.SQLiteDatabase;
      import android.database.sqlite.SQLiteOpenHelper;
      import android.util.Log;
  
      import com.example.amrapali.bookreviews.Book;
  
      public class SqlHelper extends SQLiteOpenHelper {
          //Database Version
          private static final int DATABASE_VERSION = 4;
          // Database Name
          private static final String DATABASE_NAME = "BookDB";
  
          // Books table name
          private static final String TABLE_BOOKS = "books";
  
          // Books Table Columns names
          private static final String KEY_ID = "id";
          private static final String KEY_TITLE = "title";
          private static final String KEY_AUTHOR = "author";
  
  
          public SqlHelper(Context context) {
              super(context, DATABASE_NAME, null, DATABASE_VERSION);
          }
  
          @Override
          public void onCreate(SQLiteDatabase db) {
              // SQL statement to create book table
              String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
                      "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                      "title TEXT, "+
                      "author TEXT )";
  
              // create books table
              db.execSQL(CREATE_BOOK_TABLE);
          }
          @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
              // Drop older books table if existed
              db.execSQL("DROP TABLE IF EXISTS books");
  
              // create fresh books table
              this.onCreate(db);
  
              String upgradeQuery = "ALTER TABLE books ADD COLUMN rating TEXT";
              String upgradeQuery2 = "ALTER TABLE books ADD COLUMN imagename TEXT";
              if (oldVersion == 3 &amp;&amp; newVersion == 4){
                  db.execSQL(upgradeQuery);
                  db.execSQL(upgradeQuery2);
              }
  
          }
  
          /*CRUD operations (create "add", read "get", update, delete) */
  
          public void addBook(Book book){
              Log.d("addBook", book.toString());
              // 1. get reference to writable DB
              SQLiteDatabase db = this.getWritableDatabase();
  
              // 2. create ContentValues to add key "column"/value
              ContentValues values = new ContentValues();
              values.put(KEY_TITLE, book.getTitle()); // get title
              values.put(KEY_AUTHOR, book.getAuthor()); // get author
  
              // 3. insert
              db.insert(TABLE_BOOKS, // table
                      null, //nullColumnHack
                      values); // key/value -&gt; keys = column names/values
  
              // 4. Close dbase
              db.close();
          }
          // Get All Books
          public List&lt;Book&gt; getAllBooks() {
              List&lt;Book&gt; books = new LinkedList&lt;Book&gt;();
  
              // 1. build the query
              String query = "SELECT  * FROM " + TABLE_BOOKS;
  
              // 2. get reference to writable DB
              SQLiteDatabase db = this.getWritableDatabase();
              Cursor cursor = db.rawQuery(query, null);
  
              // 3. go over each row, build book and add it to list
              Book book = null;
              if (cursor.moveToFirst()) {
                  do {
                      book = new Book();
                      book.setId(Integer.parseInt(cursor.getString(0)));
                      book.setTitle(cursor.getString(1));
                      book.setAuthor(cursor.getString(2));
                      book.setRating(cursor.getString(3));
                      book.setImageName(cursor.getString(4));
  
                      // Add book to books
                      books.add(book);
  
                  } while (cursor.moveToNext());
              }
  
              Log.d("getAllBooks()", books.toString());
  
              return books; // return books
          }
          // Updating single book
              public int updateBook(Book book, String newTitle, String newAuthor) {
  
  
              // 1. get reference to writable DB
              SQLiteDatabase db = this.getWritableDatabase();
  
              // 2. create ContentValues to add key "column"/value
              ContentValues values = new ContentValues();
              values.put("title", book.getTitle()); // get title
              values.put("author", book.getAuthor()); // get author
  
              // 3. updating row
              int i = db.update(TABLE_BOOKS, //table
                      values, // column/value
                      KEY_ID +" = ?", // selections
                      new String[] { String.valueOf(book.getId()) }); //selection args
              // 4. close dbase
              db.close();
              Log.d("UpdateBook", book.toString());
              return i;
  
          }
          // Deleting single book
          public void deleteBook(Book book) {
  
              // 1. get reference to writable DB
              SQLiteDatabase db = this.getWritableDatabase();
  
              // 2. delete
              db.delete(TABLE_BOOKS,
                      KEY_ID + " = ?",
                      new String[] { String.valueOf(book.getId()) });
  
              // 3. close
              db.close();
  
              Log.d("deleteBook", book.toString());
          }
  
          public int getIds(Book book){
  
              String selectQuery = "Select id from books";
              SQLiteDatabase database = this.getReadableDatabase();
              Cursor c = database.rawQuery(selectQuery, null);
              c.moveToFirst();
              int total = c.getCount();
              return  total;
  
          }
  
          public Set&lt;String&gt; getTitle()
          {
              Set&lt;String&gt; set = new HashSet&lt;String&gt;();
              String selectQuery= "select * from " + TABLE_BOOKS;
              SQLiteDatabase db = this.getReadableDatabase();
              Cursor cursor  = db.rawQuery(selectQuery,null);
              if
                      (cursor.moveToFirst())
              {
                  do
                  {
                      set.add(cursor.getString(1));
                      //get title  column's  value
                  }
                  while
                          (cursor.moveToNext());
              }
              cursor.close();
              db.close();
              return
                      set;
          }
  
          public int getCount(String condition) {
  
              int total=0;
              if (condition=="Get Record Count")
              {
                  String selectQuery = "Select Count(*) from" + TABLE_BOOKS;
                  SQLiteDatabase database = this.getReadableDatabase();
                  Cursor c = database.rawQuery(selectQuery, null);
                  c.moveToFirst();
                  total= c.getCount();
              }
              return total;
          }
  
  
          public StringBuilder getHighestRating(String condition) {
              StringBuilder s = null;
              if (condition == "Get Highest Rated Title(s)") {
                  s = new StringBuilder();
                  String selectQuery = "select max(rating) from " + TABLE_BOOKS;
                  SQLiteDatabase db = this.getReadableDatabase();
                  Cursor cursor = db.rawQuery(selectQuery, null);
                  if (cursor.moveToFirst()) {
                      do {
                          s.append(cursor.getString(3)); //get rating's value
                      }
                      while (cursor.moveToNext());
                  }
                  cursor.close();
                  db.close();
              }
  
                  return s;
  
          }
  
          public StringBuilder getLowestRating(String condition) {
              StringBuilder s = null;
              if (condition == "Get Highest Rated Title(s)") {
                  s = new StringBuilder();
                  String selectQuery = "select min(rating) from " + TABLE_BOOKS;
                  SQLiteDatabase db = this.getReadableDatabase();
                  Cursor cursor = db.rawQuery(selectQuery, null);
                  if (cursor.moveToFirst()) {
                      do {
                          s.append(cursor.getString(3)); //get rating's value
                      }
                      while (cursor.moveToNext());
                  }
                  cursor.close();
                  db.close();
              }
  
              return s;
  
          }
  
      }
  </code></pre>