title: Illegal State Exception while opening a SQLite database in android
body: <p>So, I have a class, named DatabaseHandler that inherits SQLiteOpenHelper. This class is incharge of managing a database that copies information from an online database to the cellphone. Now, the problem is that when I call its <code>getQuestionsCount()</code> method, which, as the name sugests, counts the number of items, it crashes. It crashes on the line that calls its <code>getReadableDatabase()</code> method. It tells me it has an IllegalStateException. What's going on?</p>
  
  <p>Code on the activity that crashes. Checks if it already has questions stored for usage:</p>
  
  <pre><code>DatabaseHandler db = new DatabaseHandler(getApplicationContext());
  
  if(db.getQuestionsCount() == 0)
      if(!isNetworkAvailable() || !canConnectToServer())
          return -2;
  else
      if(!isNetworkAvailable() || !canConnectToServer())
          return -3;
  </code></pre>
  
  <p>parts of my DatabaseHandler class:</p>
  
  <pre><code>public class DatabaseHandler extends SQLiteOpenHelper
  {
  ...
      public DatabaseHandler(Context context)
      {
          super(context, DATABASE_NAME, null, DATABASE_VERSION);
      }
      ...
  
      @Override
      public void onCreate(SQLiteDatabase db)
      {
          String CREATE_QUESTIONS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_QUESTIONS + "("
              + KEY_ID + " INTEGER PRIMARY KEY," + KEY_QUESTION + " TEXT NOT NULL,"
              + KEY_CATEGORY + " INTEGER NOT NULL," + KEY_ANSWER_1 + " TEXT NOT NULL,"
              + KEY_ANSWER_2 + " TEXT NOT NULL," + KEY_ANSWER_3 + " TEXT NOT NULL,"
              + KEY_ANSWER_4 + " TEXT NOT NULL," + KEY_DATE_POSTED + " TEXT NOT NULL)";
          db.execSQL(CREATE_QUESTIONS_TABLE);
  
          db.close();
      }
      ...
  
      public int getQuestionsCount()
      {
          String countQuery = "SELECT  * FROM " + TABLE_QUESTIONS;
          SQLiteDatabase db = this.getReadableDatabase(); //&lt;-- ERROR ON THIS LINE
          Cursor cursor = db.rawQuery(countQuery, null);
          int count = cursor.getCount();
          cursor.close();
  
          // return count
          return count;
      }
  }
  </code></pre>