Android Programming Tutorials

(Romina) #1
The Restaurant Store

Step #7: Change our Adapter and Wrapper......................................


Of course, our existing RestaurantAdapter extends ArrayAdapter and cannot


use a Cursor very effectively. So, we need to change our RestaurantAdapter


into something that can use a Cursor...such as a CursorAdapter. Just as an


ArrayAdapter creates a View for every needed item in an array or List,


CursorAdapter creates a View for every needed row in a Cursor.


A CursorAdapter does not use getView(), but rather bindView() and


newView(). The newView() method handles the case where we need to inflate


a new row; bindView() is when we are recycling an existing row. So, our


current getView() logic needs to be split between bindView() and newView().


Replace our existing RestaurantAdapter implementation in LunchList with


the following:


class RestaurantAdapter extends CursorAdapter {
RestaurantAdapter(Cursor c) {
super(LunchList.this, c);
}

@Override
public void bindView(View row, Context ctxt,
Cursor c) {
RestaurantHolder holder=(RestaurantHolder)row.getTag();

holder.populateFrom(c, helper);
}

@Override
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row, parent, false);
RestaurantHolder holder=new RestaurantHolder(row);

row.setTag(holder);

return(row);
}
}

Then, you need to make use of this refined adapter, by changing the model


in LunchList from an ArrayList to a Cursor. After you have changed that data


99
Free download pdf