Reputation: 1540
i'm trying to populate a ListView from a SQliteDatabase with Cursor and Loader, but all items are displayed in total disorder
My CursorAdapter class
@Override
public void bindView(View view, Context context, Cursor c) {
ItemHolder holder = null;
try{
holder = (ItemHolder) view.getTag();
} catch (Exception e){
e.printStackTrace();
}
if(holder != null){
System.out.println("b "+holder.position);
}
}
@Override
public View newView(Context context, Cursor c, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View nView = inflater.inflate(layoutID, parent, false);
ItemHolder holder = new ItemHolder();
System.out.println("a "+c.getPosition());
holder.position = c.getPosition();
nView.setTag(holder);
return nView;
}
Logcat output after a single full scroll return (a is position in newView() and b in bindView() )
a 0
b 0
a 1
b 1
a 2
b 2
b 0
instead of
a 0
b 0
a 1
b 1
a 2
b 2
a 3
b 3
A check of the cursor in the adapter return correct data
c.moveToFirst();
for(int i = 0; i < c.getCount(); i++){
System.out.println(i+" "+c.getString(c.getColumnIndex(COL_NAME)));
c.moveToNext();
}
I use the latest anroid.support.v4 library
Upvotes: 0
Views: 136
Reputation: 13957
You need to add an ORDER BY
clause to your SQL statement, that sorts the result of your query. Check out the documentation or this example for more details.
Sample:
SELECT * FROM <table> ORDER BY <column>;
p.s.: if you are using database.query(...)
you can add parameter for the sort column here (see orderBy
):
query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having, String orderBy)
Check out the Android documentation.
Upvotes: 1