How to set the arraylist item to be add in to reve

2019-08-20 16:31发布

问题:

In My Application, I am going to store name of all the available tables from my database with this code:

     public ArrayList<Object> showAllTable()
  {
      ArrayList<Object> tableList = new ArrayList<Object>();

      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();

      return tableList;

  }

Yes i am able to store it. But while i am going to display it in to ListView, it will display in such way that last created shown at last. I want to display the list of the table as Last created, display first in to ListView.

Please help me, What should I have to do in my code to set such way of displaying tables?

回答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:

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

Or descending:

String SQL_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
   }
}


回答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;
}