2010-10-31 49 views
0

我寫了一個小型的android應用程序,它捕獲一些數據並將其顯示在一個ListView中。Android SQL查詢不是訂購數據

我想讓列表按升序排列(無概率)。但是,當我添加一個新的項目時,即使重新加載視圖/應用程序,它仍然在列表的底部。看來唯一被排序的數據是在數據庫OnCreate()方法中創建的條目。

我不確定要提供什麼代碼,但是我將首先展示DBAdapter類的片段,然後從主應用程序類中展開。

數據庫建設查詢:

private static final String DATABASE_CREATE = 
    "create table "+ DATABASE_TABLE 
    + "(" 
    + FIELD_ROWID+" integer primary key autoincrement, " 
    + FIELD_NAME +" varchar(30) not null, " + FIELD_TELEPHONE + " varchar(20) not null, " 
    + FIELD_ADDRESS + " text not null," 
    + FIELD_URL + " varchar(255) not null);"; 

函數來獲取數據的列表:

public Cursor getRestaurants() 
{ 
Cursor result = null; 
try{ 
    result = db.query(DATABASE_TABLE, new String[] {FIELD_ROWID, FIELD_NAME}, null, null, null, null, FIELD_NAME+" ASC"); 
} 
catch (Exception e) 
{ 
    Log.v("applog", e.getMessage()); 
} 
return result; 
} 

這裏的主要方法的一個片段。在這裏你可以看到我正在調用上面顯示的getRestaurants()函數。我很難理解爲什麼數據沒有被排序。

任何建議非常感謝。提前致謝。

public class Assignment2 extends ListActivity { 

// Set up some global variables. 
private static final int ADD_NEW_ID = Menu.FIRST; 
private static final int CLOSE_APP_ID = ADD_NEW_ID+1; 
private final DBAdapter db = new DBAdapter(this); 
private static CursorAdapter curAdapter = null; 
private static Cursor rawData = null; 
@Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 

     db.open(); // Open connection to restaurant db. 

    rawData = db.getRestaurants(); 
    Log.v("applog", rawData.getCount()+" Restaurants loaded from DB."); 

    if(rawData.getCount() == 0) 
    { 
     Toast.makeText(getApplicationContext(), "No restaurants found.", Toast.LENGTH_SHORT).show(); 
    } 
    try 
    { 
     /* The following two arrays are used to map DB fields to ListView items 
     * From a custom layout file. 
     */ 
     // Array of db fields to be used when converting cursor to ListView 
      String[] strFields = { "name", BaseColumns._ID }; 
      // Array of listview id's to be used when populating the ListView 
      int[] intFields = { R.id.first }; 

      curAdapter = new SimpleCursorAdapter(this, R.layout.row, rawData, strFields, intFields); 
    } 
    catch (Exception e) 
    { 
     Log.v("applog", e.getMessage()); 
    } 

    // Apply the converter cursor to the current ListView 
    setListAdapter(curAdapter); 
     db.close(); // Close connection to restaurant db. 

回答

0

林不知道究竟你的問題是什麼,但是,這一切看起來不錯減去幾行代碼我有,當我從我的新數據的回調插入

 if(cursor!=null)cursor.requery(); 
     adapter.notifyDataSetChanged(); 

希望這將解決您的問題。

+0

謝謝,但該代碼不能解決它。 當餐廳名稱以大寫字母開頭時,程序正常工作。然後它是排序數據的一部分。 但是,如果名稱以小寫字母開頭,那麼它不是排序的一部分,只是停留在列表的底部.. **令人困惑的** – conor 2010-10-31 22:16:33

+0

我猜它按ASCII值對數字進行排序 – schwiz 2010-11-01 18:44:01

+0

其中是添加/刪除項目的代碼?你是否將它提交給數據庫,或只是將它從適配器中移除> – Jim 2010-11-01 21:23:11