SyntaxHighlighter JS

2013-03-12

Android ListView Tutorial: simple_list_item_2 and SimpleAdapter

This tutorial demonstrates how to display an array of Java enum in the Android UI. This example is also applicable if using an array or List of JavaBeans or plain Java Objects.

Core Concepts Covered
  1. Use the built-in android.R.layout.simple_list_item_2 to create an Android UI List.
  2. Use android.widget.SimpleAdapter to display an array of Java enum in the Android UI List.
Summary Technical Steps
  1. Create class extending android.app.ListActivity.
  2. Obtain data as an array of Java enum entries.
  3. Convert the array of enum into a List<Map<String, String>> format that will be used by the android.widget.SimpleAdapter constructor.
  4. Create an android.widget.SimpleAdapter that connects the List<Map<String, String>> data to android.R.layout.simple_list_item_2.
  5. Bind the android.widget.ListAdapter using the ListActivity.setListAdapter method.
Detailed Technical Steps

1. Create class extending android.app.ListActivity.

public class MainActivity extends ListActivity {

    @Override
    protected final void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}
    2. Obtain data as an array of Java enum entries, using the built-in enum method values(), e.g. UsState.values() .
    For this tutorial, we will use an enum containing the 13 US original colonies. View the full UsState.java code listing.

    public enum UsState {
        DE("Delaware"),
        PA("Pennsylvania"),
        NJ("New Jersey");

           private String stateName;

        private UsState(final String name) {
            this.stateName = name;
        }

        public String getStateName() {
    return this.stateName;
        }

        public String getAbbreviation() {
    return this.name();
        }

    }

    3. Convert the array of enum into a List<Map<String, String>> format that will be used by the android.widget.SimpleAdapter constructor.

    private static final String TEXT1 = "text1";
    private static final String TEXT2 = "text2";

    private List<Map<String, String>> convertToListItems(final UsState[] states) {
        final List<Map<String, String>> listItem =
          new ArrayList<Map<String, String>>(states.length);

        for (final UsState state: states) {
            final Map<String, String> listItemMap = new HashMap<String, String>();
    listItemMap.put(TEXT1, state.getStateName());
    listItemMap.put(TEXT2, state.getAbbreviation());
    listItem.add(Collections.unmodifiableMap(listItemMap));
        }

        return Collections.unmodifiableList(listItem);
    }

    The convertToListItems method converts an array of UsState into a List of Map. The List of Map will be used as part of the constructor for a SimpleAdapter.

    Each element in the List will correspond to a row in the Android UI list. The Map<String, String> maps the attributes on the Object to the android.R.id.text1 and android.R.id.text2 UI fields.

    For example, if you input
    UsState[] =
        [ DE("Delaware"),
          PA("Pennsylvania"),
          NJ("New Jersey")
        ];

    the output will be
    List<Map<String, String>> =
        [ {text1="Delaware", text2="DE"},
          {text1="Pennsylvania", text2="PA"},
          {text1="New Jersey", text2="NJ"}
        ];
       
    4. Create an android.widget.SimpleAdapter in the ListActivity class from step 1 that connects the List<Map<String, String>> data to android.R.layout.simple_list_item_2.

    private ListAdapter createListAdapter(final UsState[] states) {
        final String[] fromMapKey = new String[] {TEXT1, TEXT2};
        final int[] toLayoutId = new int[] {android.R.id.text1, android.R.id.text2};
        final List<Map<String, String>> list = convertToListItems(states);

        return new SimpleAdapter(this, list,
                              android.R.layout.simple_list_item_2,
                                 fromMapKey, toLayoutId);
    }


    In the createListAdapter method, the constructor of the SimpleAdapter binds the keys from the Map<String, String> created in convertToListItems to the android.R.id.text1 and text2. It associates "text1" from the fromMapKey array to the android.R.id.text1 in the toLayoutId array. When the ListView needs to show text for the android.R.id.text1 ID, it executes a Map.get("text1") to get the String value to display, e.g. Delaware.
       
    5. Bind the android.widget.ListAdapter using the ListActivity.setListAdapter method.

    public class MainActivity extends ListActivity {

        @Override
        protected final void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

    final UsState[] states = UsState.values();
            final ListAdapter listAdapter = createListAdapter(states);
            setListAdapter(listAdapter);
        }
    }

    View the full MainActivity.java code listing.

    The final result will look like this




    Source Code: Git | SVN | Download Zip

    6 comments:

    1. Java is a very easy to use language once u get a hold of it.... if anyone is a beginner in java then they should attend some interesting java focused conferences which gives a huge knowledge abt the language nd very interesting, easy tips nd tricks which are very useful... few of the famous java conferences are Javapolis (devox), JavaOne, and recently i received a mail from oracle regarding their JavaOne conference.. They have many interesting sessions lined up fr this year... you can take a look at their sessions related topics here: http://bit.ly/YMPeJ8
      I myself hoping to attend several sessions about Core Java Platform; JavaFX, Java Embedded, and Java Card and many more.

      ReplyDelete
    2. mListAdapter = new FirebaseListAdapter(getActivity(), ChatMessage.class,
      android.R.layout.two_line_list_item, mFirebaseRef) {
      @Override
      protected void populateView(View v, ChatMessage model, int position) {
      ((TextView)v.findViewById(android.R.id.text1)).setText(model.getName());
      ((TextView)v.findViewById(android.R.id.text2)).setText(model.getText());
      }
      };


      How can i change this two textview ??

      ReplyDelete
    3. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

      ReplyDelete
    4. Good post and I like it very much. By the way, anybody try this app development company for iOS and Android? I find it is so professional to help me boost app ranking and increase app downloads.

      ReplyDelete