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"?>
<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal"
   android:padding="10dp" >
   <TextView
       android:id="@+id/name"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_weight="1"
       android:padding="5dp"
       android:textSize="18dp" />
   <TextView
       android:id="@+id/code"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:padding="5dp" />
</LinearLayout>

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;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(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);
               countries.add(country);
           }
           //  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
           setListAdapter(adapter);
       }
   }
OUTCOME.

DOWNLOAD

REFERENCES


.

No comments:

Post a Comment