Tuesday, August 11, 2015

List Activity Simple Adapter Hash Map

List Activity Simple Adapter Hash Map
Using Android Studio 1.4

1) Create New Project

Application Name: MyListActivitySimpleAdapterHashMap1
Select API 14:Android 4.0 (IceCreamSandwich)
Follow the wizard to create New Empty Activity.
Deselect “Generate Layout File”
We do not require ListView Layout as List Activity has a built-in layout.
However, we need to define a Row Layout and Custom Adapter in order to implement HashMap structure

2) Add Row Layout

2.1) res/layout/row_layout.xml

<?xml version="1.0" encoding="utf-8"?>
   android:padding="10dp" >
       android:textSize="18dp" />
       android:padding="5dp" />

3) Edit MainActivity.java

package com.notarazi.mylistactivitysimpleadapterhashmap1;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
public class MainActivity extends ListActivity {
       ArrayList<HashMap<String, String>> countries;
       protected void onCreate(Bundle savedInstanceState) {
           String[] locales = Locale.getISOCountries();
           countries new ArrayList<HashMap<String, String>>();
           for (String countryCode : locales) {
               Locale obj = new Locale("", countryCode);
               HashMap<String, String> country = new HashMap<String, String>();
               String country_name = obj.getDisplayCountry();
               String country_code = obj.getCountry();
               country.put("name", country_name);
               country.put("code", country_code);
           //  keys of hashmap
           String[] from = { "name""code" };
           // view id's to which data to be binded
           int[] to = { R.id.name, R.id.code };
           //Creating Adapter
           ListAdapter adapter = new SimpleAdapter(MainActivity.thiscountries,
                   R.layout.row_layout, from, to);
           //Setting Adapter to ListView




No comments:

Post a Comment