gowri
gowri

Reputation: 681

What's the best way to use Adapters on Android?

What's the best way to use Adapters on Android? We can use it for several customized operations. By using the adapter we will include some pre-implemented methods. When should I use these methods? How can we improve our apps' performance by using the Adapter implemented methods?

public int getCount() {
        // TODO Auto-generated method stub
        return country.length;
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }
}

Upvotes: 1

Views: 251

Answers (3)

user1833024
user1833024

Reputation:

Look out this sample example and the link

public class GridDemo extends Activity implements AdapterView.OnItemClickListener {
    private TextView selection;
    private static final String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi", "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante", "porttitor", "sodales", "pellentesque", "augue", "purus"};

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        selection=(TextView)findViewById(R.id.selection);
        GridView g=(GridView) findViewById(R.id.grid);
        g.setAdapter(new ArrayAdapter<String>(this, R.layout.cell, items));
        g.setOnItemClickListener(this);
    }

    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        selection.setText(items[position]);
    }
}

You can get an idea for this Adapters..

Upvotes: 2

TieDad
TieDad

Reputation: 9899

getCount() is a must. It tells ListView, GridView or etc that how many items to display. getItem() and getItemId() in many cases (if you implement getView() by your own code) are actually optional, they are just helper methods. There methods are basic to an adapter, it doesn't help on performance improvement. I think getView()'s implementation effect performance the most.

Upvotes: 0

Andy
Andy

Reputation: 10830

BaseAdapter is a great choice for simply using ListView or GridView. But if you want to get data from the database, a CursorAdapter is much more well suited for that, though the doc says this is for ListView. So a SimpleCursorAdapter would be the other type you'd use if you want both ListView and GridView usage when pertaining to showing data you get from a database. But of course knowing your implementation would help me better give you the best choice.

I should also add since I saw it on one of the comments, ArrayAdapter is basically a BaseAdapter, but the difference being it takes arrays of arbitrary objects a.k.a best suited for arrays straight out of the box.

Upvotes: 1

Related Questions