0

Hello fellow programmers, i have this code

public class IdiomsCollection {

private ArrayList<Idiom> idiomsList = new ArrayList<Idiom>();

public IdiomsCollection() {
    loadIdioms();
}

private void loadIdioms() {

    //creating new items in the list
    Idiom i1 = new Idiom();
    i1.setPhrase("Piece of cake");
    i1.setMeaning("When something is easy to do");
    i1.setUsage("That test that I took was a piece of cake");
    idiomsList.add(i1);
}
}

I want to add the content of my ArrayList to my onCreate() method in another class, so when i run the app, i see my list on the screen. I am not sure how to do that, can anybody help me?

Lucas
  • 71
  • 1
  • 2
  • 6
  • use `BaseAdapter` as parent and implement your adapter on that ArrayList collection – Marek Sebera Apr 24 '13 at 19:06
  • @MarekSebera could you give me an example, possibly using the code i provided? i would really appreciate that – Lucas Apr 24 '13 at 19:11
  • Lucas: no, i won't give you example using provided code, but here is my implementation, and you can use it ;-) https://github.com/smarek/Simple-Dilbert/blob/master/src/com/mareksebera/dilbert/FavoritedAdapter.java – Marek Sebera Apr 24 '13 at 19:17

2 Answers2

0

Make use of inheritance. It is create class like this

public class IdiomsCollection extends ArrayList<Idiom> {


public IdiomsCollection() {
    loadIdioms();
}

private void loadIdioms() {

    //creating new items in the list
    Idiom i1 = new Idiom();
    i1.setPhrase("Piece of cake");
    i1.setMeaning("When something is easy to do");
    i1.setUsage("That test that I took was a piece of cake");
    this.add(i1);
}
}

And read how to populate ListView with data from ArrayList

Community
  • 1
  • 1
Gustek
  • 3,680
  • 2
  • 22
  • 36
0

I suggest you to use an ArrayAdapter and if you don't have particular needs you can use a standard layout for your rows in the ListView. More or less the code shoud look like:

public class IdiomsCollection {

.....
  public List<Idioms> getIdiomsList() {
     return idiomsList;
  }

}

In our Activity

public void onCreate(..) {

 ListView lv = (ListView) findViewById(R.id.listView);
 List<Idiom> idiomList = ( new IdiomsCollection()).getIdiomsList();
  final ArrayAdapter<Idiom> aAdpt =
        new ArrayAdapter<Idiom>(this,                 
               android.R.layout.simple_list_item_1, idiomListList);

  lv.setAdapter(aAdpt);  

}

Provide a toString method to the IdiomClass and a layout for the Activity. If you want to have more control on how to show Idioms data in the listview row you can implement your custom adapter. Give a look oon my blog here for ArrayAdapter you can find a working example. And also on my blog here in case you want to create your own Adapter.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
FrancescoAzzola
  • 2,666
  • 2
  • 15
  • 22