Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add extra element to cursor adapter android

I have a Cursor that contains all rows from my database. That Cursor I pass to a CursorAdapter, and display the data in a list. But I need to show one extra element in the beginning. How can I do that?

I read somewhere that maybe it can be done with a CursorWrapper, and it can inject extra values into the results. But I'm not quite sure how to do that.

If someone can show me an example (code), or have another idea how to solve this, please let me know. Thx!

like image 554
Sandra Avatar asked Sep 19 '12 10:09

Sandra


People also ask

What is cursor adapter in Android?

An easy adapter to map columns from a cursor to TextViews or ImageViews defined in an XML file. Adapter that exposes data from a Cursor to a ListView widget.

How many types of adapters are there in Android?

Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and building views for an AdapterView ( i.e. ListView or GridView). The common adapters are ArrayAdapter,Base Adapter, CursorAdapter, SimpleCursorAdapter,SpinnerAdapter and WrapperListAdapter.

How do I use CursorAdapter?

1) CursorAdapterIn BaseAdapter, view is created in getView method; in CursorAdapter, however, view is created in newView() method and elements are populated in bindView(). In the newView() method, you simply inflate the view your custom xml and return it. In the bindView() method, you set the elements of your view.


2 Answers

How about using a combination of MergeCursor and MatrixCursor as I've suggested in this question: How to insert extra elements into a SimpleCursorAdapter or Cursor for a Spinner?

like image 66
naktinis Avatar answered Oct 02 '22 20:10

naktinis


Override getCount like this:

@Override
public int getCount() {
    final int count = super.getCount();
    return count+1;
}

and who ever uses the adapter gets one extra row. Just remember to handle this in getView ie.

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(position == 0) {
            final View v = inflater.inflate(R.layout.special_suggestion, parent,false);
            final TextView tv = (TextView) v.findViewById(android.R.id.text1);
            tv.setText("Search for '" + this.keyword + "'");
            return v;
        }
        else {
            try {
                return super.getView(position, convertView, parent);
            }
            catch (IllegalStateException e) {
                Log.e(TAG, "IllegalStateException: " + e);
            }
        }
        return inflater.inflate(this.layout, parent,false);
    }
like image 41
slott Avatar answered Oct 02 '22 19:10

slott