我的数据库查询显示将值按字母顺序排序

时间:2011-09-29 19:43:34

标签: android sqlite

我一直试图在不寻求帮助的情况下解决这个问题,但我已经达到了老实说无法解决的问题。

这是我用来查询数据库的函数(我必须更改名称以保密):

public Cursor getAllItems(){
    Cursor cursor = db.query(true, DATABASE_TABLE, new String []{KEY_NAME, KEY_1,KEY_2, KEY_3,
                KEY_4, KEY_5, KEY6,
                KEY_7, KEY_8, KEY_9, KEY_10, KEY_11, KEY_12,
                KEY_13}, null, null, null, null, null, null);
    cursor.moveToFirst();

    return cursor;
}

这是我填充使用xml创建的tablelayout的地方。

public void populate(){
    db = new DBAdapter(this);

    TableLayout TL = (TableLayout)findViewById(R.id.table);        

    db.open();  
    c = db.getAllItems();       
    while(!c.isAfterLast()){
        if(Integer.toString(c.getPosition())!=null){
        TableRow TR = new TableRow(this);

        TR.setId(c.getPosition());

        TextView column1 = new TextView(this);
        TextView column2 = new TextView(this);
        TextView column3 = new TextView(this); 

        TR.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));         

        column1.setGravity(0x01);
        column1.setTextColor(0xff000000);
        column1.setTextSize(2,20);
        //column1.setText(c.getString(3)); 
        column1.setText(Integer.toString(c.getPosition()));
        TR.addView(column1);                

        column2.setGravity(0x01);
        column2.setTextColor(0xff000000);
        column2.setTextSize(2,20);
        column2.setText(c.getString(0));
        TR.addView(column2);        

        column3.setGravity(0x01);
        column3.setTextColor(0xff000000);
        column3.setTextSize(2,20);
        //column3.setText(c.getString(1));
        column3.setText(Integer.toString(TR.getId()));
        TR.addView(column3);


        TR.setOnLongClickListener(this);
        TL.addView(TR);  

        1Total += c.getDouble(1);
        2Total += c.getDouble(2);
        }
        c.moveToNext();
    }
    db.close();

如果我使用DDMS查看数据库,则所有内容都以正确的顺序显示(我插入表中的顺序)。但是,当我尝试在tablelayout中显示数据时,由于某种原因,它会根据KEY_NAME值组织值。因此,如果我将数据插入表中,如“B - C - D - A - E”,它将用“A - B - C - D - E”填充我的表格布局

有些奇怪的是我设置了它,以便在任何给定行上进行长按,生成显示其余信息的对话碎片,并且此信息是正确的。因此,如果使用上面的例子,我长时间点击显示的“C”行,那么我将实际得到“D”的数据,这是正确的。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

在SQLiteDatabase类的javadoc中,对于查询方法,它表示“传递null [对于排序顺序]将使用默认排序顺序, 可能 无序的。“ null是您传递的众多空值之一,因此 可能 的顺序是无序的,但显然 可能 请改为命令。

也许尝试使用public Cursor rawQuery (String sql, String[] selectionArgs)代替查询?

所以我觉得你的情况就像是

public Cursor rawQuery (String "SELECT DISTINCT KEY_NAME, KEY_1,KEY_2, KEY_3, KEY_4, KEY_5, KEY6, KEY_7, KEY_8, KEY_9, KEY_10, KEY_11, KEY_12, KEY_13 FROM DATABASE TABLE", null);

根据我的经验,Android SQLite以插入顺序返回rawQuery结果,虽然我不确定它是否需要。一个更可行的方法是添加自动增量键列 - 给每行一个序列号,基本上 - 然后在其上排序查询结果。