【发布时间】:2014-11-20 07:20:25
【问题描述】:
我该怎么做呢,我有 COLUMN_ID、COLUMN_NAME 和 COLUMN_INTE
COLUMN_INTE 保存长整数,我希望它显示在列表视图中,目前它不会从最高到最低降序
【问题讨论】:
标签: android database sqlite integer
我该怎么做呢,我有 COLUMN_ID、COLUMN_NAME 和 COLUMN_INTE
COLUMN_INTE 保存长整数,我希望它显示在列表视图中,目前它不会从最高到最低降序
【问题讨论】:
标签: android database sqlite integer
您需要使用 ORDER BY 子句针对您的表编写查询,该子句使用 DESC 关键字指示降序。像这样的东西应该可以工作:
string query = "SELECT COLUMN_ID, COLUMN_NAME, COLUMN_INTE FROM MY_TABLE ORDER BY COLUMN_INTE DESC";
Cursor c = db.rawQuery(query, null);
String[] columns = new String[] { "COLUMN_ID", "COLUMN_NAME"};
int[] to = new int[] {android.R.id.text1, android.R.id.text2};
try {
dataAdapter = new SimpleCursorAdapter(
this, android.R.layout.simple_list_item_2, c, columns, to, 0
);
ListView lv = (ListView) findViewById(R.id.MY_LISTVIEW);
lv.setAdapter(dataAdapter);
} catch (Exception ex) {
ex.printStackTrace();
}
【讨论】:
您有两个选择:使用为您排序的 SQL 命令,或者您可以获取整个列表并自行排序。
SQL命令排序:
// Create an object to store rows from the table
tableRowObject = new tableRowObject();
String query = "select * from STATISTICS order by COLUMN_INTE";
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount()<1) // COLUMN_INTE Not Found
{
cursor.close();
}
else
{
while(cursor.moveToNext())
{
// Get COLUMN_ID, COLUMN_NAME, COLUMN_INTE
int columnID = cursor.getInt(cursor.getColumnIndex("COLUMN_ID"));
String columnName = cursor.getString(cursor.getColumnIndex("COLUMN_NAME"));
int columnInte = cursor.getInt(cursor.getColumnIndex("COLUMN_INTE"));
// Add the variables to a new object
tableRowObject.add(columnID, columnName, columnInte);
}
cursor.close();
}
给自己排序:
// Create an object to store rows from the table
tableRowObject = new tableRowObject();
String query = "select * from STATISTICS";
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount()<1) // COLUMN_INTE Not Found
{
cursor.close();
}
else
{
while(cursor.moveToNext())
{
// Get COLUMN_ID, COLUMN_NAME, COLUMN_INTE
int columnID = cursor.getInt(cursor.getColumnIndex("COLUMN_ID"));
String columnName = cursor.getString(cursor.getColumnIndex("COLUMN_NAME"));
int columnInte = cursor.getInt(cursor.getColumnIndex("COLUMN_INTE"));
// Add the variables to a new object
tableRowObject.add(columnID, columnName, columnInte);
}
cursor.close();
}
// Sort the object
【讨论】:
您也可以使用比较器进行排序。举个例子-
类 MySalaryComp 实现比较器{
@Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() < e2.getSalary()){
return 1;
} else {
return -1;
}
}
}
【讨论】: