Search code examples
androidlistviewandroid-listviewarraylist

listview with arraylist,simple adapter in android


I try to show something into listview using arraylist and simple adapter. I tried something like below but in my result shows the last names of the arraylist. What is my wrong i cant understand.

final ListView listView = (ListView) findViewById(R.id.mylist);

    ArrayList<HashMap<String, String>> list_of_bookmarks = new ArrayList<HashMap<String, String>>();

        HashMap<String, String> b = new HashMap<String, String>();

        String[] from = { "php_key","c_key","android_key","hacking_key" };
        String[] name_of_bookmarks = { "php","c","android","hacking" };

            for(int i=0;i<4;i++)
            {
              b.put(from[i],name_of_bookmarks[i]);   
              list_of_bookmarks.add(b);
            }

         };

            int[] to = { R.id.txt1,R.id.txt1,R.id.txt1,R.id.txt1};

            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), list_of_bookmarks, R.layout.list_layout, from, to);         
            listView.setAdapter(adapter);

I just want to show "php","c","android","hacking" in a listview. And what should be more efficient way to do that.I am a beginner so you may suggest a better way which should i follow


Solution

  • Main.xml

    <LinearLayout  
    
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="60dp"   >
    
    
        <ListView
            android:id="@+id/zone_list"
            android:layout_marginBottom="70dp"
            android:background="@drawable/batteryborder"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>
    
    </LinearLayout>
    

    setlanguage.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="60dp">
    
        <TextView
            android:id="@+id/tvName"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:textSize="18dp"
            android:gravity="center_vertical" />
    
    </LinearLayout>
    

    add in onCreate() of your activity file

    ListView listView;
    
    String[] from = { "php_key","c_key","android_key","hacking_key" };
    
    ArrayAdapter arrayAdapter;
    
    listView = (ListView) findViewById(R.id.zone_list); 
    
    arrayAdapter = new ArrayAdapter<>(this,R.layout.setlanguage, R.id.tvName, from);
    
    listView.setAdapter(arrayAdapter);