Search code examples
androidsqliteandroid-sqlite

Getting "Variable might not initialized error"


I am creating function for Sqlite database and getting "variable might not initialized" error. I am trying to store sqlite data in string array.


public String[] gettitle()
  {
          String title[];
          String s = "select Title from User_DB;";
          SQLiteDatabase db = getReadableDatabase();
          Cursor cursor = db.rawQuery(s,null);
          int a = 0;
          while(cursor.moveToNext())
          {

              title[a] = cursor.getString(0);
              a++;
          }
          return title;
  }

it says title[] is not initialized but I dont understand why. I clearly initialized it.


Solution

    1. You declare title. Allowed C language style is String title[]. In java one keeps the type expression together: String[] title;

         String[] title;
      

      This variable is uninitialized, reserves a memory slot for an array object, but the memory is not filled, initialized; it contains garbage. At its first usage of title the compiler issues an error.

      In contrast class fields are initialized automatically by a default: here null, but for other types 0, false, 0.0 and so on.

    2. Initialize the variable: give it an initial value.

      For arrays that means set an array object. Arrays are fixed length, cannot grow, and thus:

       String[] title;
       title = new String[10];
      

      Or shorter:

       String[] title = new String[10];
      

      Like fields also array elements are initialized with defaults, null.

      Note you initialized a: int a = 0;.

    3. Now you can use the array object through the variable:

             title[a] = cursor.getString(0);
      

      This was the point where the compiler saw the usage of a variable that still did not have a value.

    So the code becomes:

    public String[] loadTitles() {
        String[] titles = new String[100];
        String sql = "select Title from User_DB";
        SQLiteDatabase db = getReadableDatabase();
        int a = 0;
        try (Cursor cursor = db.rawQuery(sql, null)) {
            while (a < titles.length && cursor.moveToNext()) {
                titles[a] = cursor.getString(0);
                a++;
            }
        } // Calls cursor.close();
        return Arrays.copyOf(titles, a);
    }
    

    Array.copyOf(array, newLength) make copy of the original array with as new length the number of read titles.

    I have added the (weird) try-with-resources syntax which ensures that cursor is closed, even on exception or return happening inside the block.