user2573715
user2573715

Reputation: 47

Struggling with ArrayAdapter

I'm totally new to android programming, I'm trying to create a friendslist class.

First, I make an array that loads objects from a database:

friendArray = new Friend[NumberOfFriendsInDatabase];

//gets friend objects from the database, and loads them into an array
for (int i=0;i<NumberOfFriendsInDatabase;i++){
    friendArray[i]=new Friend("","","");//swap this with an object or data from database handler.

then I create a listview where I want the array to be visually represented:

friendListView  =(ListView) findViewById(R.id.FriendsListView1);

and at last, I understand that I need to use an adapter to achieve this, and this is where I'm confused.

friendListAdapter = ArrayAdapter();

I'm having trouble creating the adapter, and I can't make sense of the official documentation. All I want is the friendArray in an adapter that I can use with listView.

Upvotes: 2

Views: 68

Answers (1)

Steve Benett
Steve Benett

Reputation: 12933

You can use an ArrayAdapter like this:

// A Collection which holds your values
List<YourFriendObject> list = new ArrayList<YourFriendObject>();

// fill the Collection with your data
// you should use for-each but I dont know your object
for (int i = 0; i < friendArray.length; i++)
  list.add(friendArray[i]);

// The ArrayAdapter takes a layout, in this case a standard one
// and the collection with your data
ArrayAdapter<YourFriendObject> adapter = new ArrayAdapter(this,
    android.R.layout.simple_list_item_1, list);

 // provide the adapter to your listview
frienListView.setAdapter(adapter);

Hope this helps to understand the basics. Here is a nice tutorial about this topic.

Upvotes: 2

Related Questions