I have an app which uses a Listview to display Lectures. The Lectures are colour coded according to their type. I used a custom adapter to control the different colours of each lecture. I call the adapter using the code below –
cursor = myDbHelper.getReadableDatabase().rawQuery(sql, null);
startManagingCursor(cursor);
adapter = new Lectures_Adapter(this,R.layout.menu_item,cursor,FROM,TO);
menuList.setAdapter(adapter);
This all works ok until I re-order the Lectures, say by Location. The code I use is –
Cursor newCursor = myDbHelper.getReadableDatabase().rawQuery(sqlStr, null);
adapter.changeCursor(newCursor);
The code in my custom adapter (Lectures_Adapter) is below but is not called when the Lectures are re-ordered.
public class Lectures_Adapter extends SimpleCursorAdapter {
private Context appContext;
private int layout;
private Cursor mycursor;
public Lectures_Adapter(Context context, int layout, Cursor c, String[] from,int[] to) {
super(context, layout, c, from, to);
this.appContext=context;
this.layout=layout;
this.mycursor=c;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = super.getView(position, convertView, parent);
try {
if (position > 0)
{
RelativeLayout rowFill = (RelativeLayout) convertView.findViewById(R.id.rowFill);
String title = mycursor.getString(1);
int myColor = 0;
int myPos = title.indexOf("Nursing");
int myPos2 = title.indexOf("Masterclass");
if (myPos >= 0)
{
myColor = Color.parseColor("#99FF66");
}
else if (myPos2 >= 0)
{
myColor = Color.parseColor("#FF99FF");
}
else
{
myColor = Color.parseColor("#FFFF66");
}
convertView.findViewById(R.id.rowFill).setBackgroundColor(myColor);
}
}catch(Exception e) {
}
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) this.appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(this.layout,null);
} else {
convertView = (View) convertView;
}
return view;
}
}
Can somebody please tell me how I can re-order my Listview dynamically and call me custom adapter each time.
The problem is that your code in getView() gets its data from the class variable
mycursor, but when you call changeCursor, themycursorvariable is not getting updated, so you still see the original list. Rather than usingmycursor, you should callgetCursor()instead.