Skip to content Skip to sidebar Skip to footer

How To Set The Arraylist Item To Be Add In To Reverse Order?

In My Application, I am going to store name of all the available tables from my database with this code: public ArrayList showAllTable() { ArrayList

Solution 1:

There are several ways to do it. The easiest is probably to change your SQL call by adding ORDER BY. Here's something you can try out:

To order the items ascending:

StringSQL_GET_ALL_TABLES="SELECT name FROM sqlite_master WHERE type='table' ORDER BY name ASC";

Or descending:

StringSQL_GET_ALL_TABLES="SELECT name FROM sqlite_master WHERE type='table' ORDER BY name DESC";

Alternative solution

Another option would be to do it like you're doing it right now, and instead go through the Cursor from the last to the first item. Here's some pseudo code:

if (cursor.moveToLast()) {
   while (cursor.moveToPrevious()) {
      // Add the Cursor data to your ArrayList
   }
}

Solution 2:

before return the values just call the method

Collections.reverse(tableList);

see the full code

public ArrayList<Object> showAllTable()

{ 
 ArrayList tableList = new ArrayList();

 String SQL_GET_ALL_TABLES = "SELECT name FROM sqlite_master WHERE type='table'";
 Cursor cursor = db.rawQuery(SQL_GET_ALL_TABLES, null);
 cursor.moveToFirst();

 if (!cursor.isAfterLast()) 
 {
  do 
  {
      if(cursor.getString(0).equals("android_metadata"))
      {
          //System.out.println("Get Metadata");continue;
      }
      else
      {
          tableList.add(cursor.getString(0));
      }
  }
  while (cursor.moveToNext());
 }
 cursor.close();
 Collections.reverse(tableList);
 return tableList;
}

Post a Comment for "How To Set The Arraylist Item To Be Add In To Reverse Order?"