title: Android Studio - Sqlite: get random row data using cursor
body: <p>I have created an Sqlite table called <code>"TABLE1_NAME"</code> which contains only one column with name car_name;</p>
  
  <p>In my getdata() fucntion, I am using <code>"ORDER BY RANDOM() LIMIT 1"</code> in the db query to get car name with random position, however, the result is always being stored as null.</p>
  
  <p>Please note: String carname already declared as a global variable.</p>
  
  <p>Here's my code:</p>
  
  <pre><code>public String getData()
  {
      sqLiteDatabase=this.getReadableDatabase();
      Cursor cursor;
      cursor= sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE1_NAME+" ORDER BY RANDOM() LIMIT 1",null);
  
      if(cursor!=null &amp;&amp; cursor.moveToFirst())
      {
          carName=cursor.getString(cursor.getColumnIndex("car_name"));
          cursor.close();
      }
      return carName; //carname=null --&gt; null is being stored in carname
  }
  </code></pre>
  
  <p>Please guide me, where am I going wrong; Thanks.</p>
  
  <p><strong>Here is my edited code, after incorporating all your suggestions, still the result is null:</strong></p>
  
  <pre><code> public String getData()
  {
      String carName = null;
      sqLiteDatabase=this.getReadableDatabase();
      Cursor cursor;
      cursor= sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE1_NAME+" ORDER BY RANDOM() LIMIT 1",null);
  
      if(cursor!=null &amp;&amp; cursor.moveToFirst() &amp;&amp; !cursor.isAfterLast())
      {
          carName=cursor.getString(cursor.getColumnIndexOrThrow("car_name"));
          cursor.close();
      }
      return carName;
  }
  </code></pre>
  
  <p><strong>This is how i am inserting data into the database in the first place:</strong> </p>
  
  <pre><code> public void insertCarData(String[] cars)
  {
      sqLiteDatabase=this.getReadableDatabase();
      ContentValues cv = new ContentValues();
  
      for(int i=0;i&lt;cars.length;i++)
      {
          cv.put(TABLE_CAR_NAME,cars[i]);
      }
      sqLiteDatabase.insert(TABLE1_NAME,null,cv);
      sqLiteDatabase.close();
  }
  </code></pre>
  
  <p>The issue may be occuring from here. Thanks.</p>