我有一个列表视图和一个数据库我想在另一个活动中显示数据库中的数据,所以我为列表视图创建了一个OnItemClickListener。 现在我得到了ClickListener的位置,但是因为我已经使我的适配器显示数据所以来自用户的最新输入在顶部。我想要改变onClick的位置。
目前我得到: 1 2 3 4
但我需要: 4 3 2 1
因为数据库ID。
例如,如果用户单击列表中的位置3,我希望数据库返回第3行。
ListView:
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(getActivity(), JornalListViewClick.class);
myIntent.putExtra("intVariableName",position);
startActivity(myIntent);
}
});
数据库的getRows:
public Cursor getAllRowre(){
String where=null;
Cursor cursor=db.query(true, DATABASE_TABLE, ALL_KEY, where, null, null, null,ID_KEY + " DESC", null);
if(cursor!=null){
cursor.moveToFirst();
}
return cursor;
}
我想要显示数据的活动:
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
intValue++;
text=(TextView) findViewById(R.id.textViewUserInputFromListClicked);
Cursor cursor=dbJ.getRowUserInput(intValue+"");
if(cursor.moveToFirst()){
do{
String mes=cursor.getString(0);
text.setText(mes);
}while(cursor.moveToNext());
}
答案 0 :(得分:0)
另一种方式:
使用POJO存储检索到的每一行
实现Comparator并使用Collections.sort(List,Comparator)在将其放入适配器之前对其进行排序
public class MyData{
private String field;
// getter and setter
}
从数据库中检索String后,您可以实例化MyData类并将字符串(或更多字段)设置到实例中。将所有结果放入集合中。 E.g:
Vector<MyData> listOfResults=new Vector<MyData>();
if(cursor.moveToFirst()){
do{
String mes=cursor.getString(0);
MyData instance=new MyData();
listOfResults.add(instance);
}while(cursor.moveToNext());
}
return listOfResults;
从数据库中检索数据后,您想要对其进行排序,对吧?试试这个:
Collections.sort(listOfResults,new Comparator<MyData>(){
public int compareTo(MyData a,MyData b){
return a.getField().compareTo(b.getField());
}
});
在包含ListView的Activity内,创建一个实现ListAdapter的私有类。 E.g:
private class MyListAdapter implements ListAdapter{
private Vector<MyData> data;
public MyListAdapter(Vector<MyData> list){
data=list;
}
/*** other methods you need to implement ***/
}
通过提供从数据库访问方法获得的Vector来实例化MyListAdapter。
然后在数据就绪后调用Activity中的ListView的setAdapter(ListAdapter)。