listview with arraylist,simple adapter in android
Asked Answered
A

5

11

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

Andes answered 5/9, 2013 at 6:2 Comment(2)
Its display only last value ?Myriad
4 times the last value like "hacking,hacking,hacking,hacking"Andes
B
7

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);
Bagehot answered 5/9, 2013 at 7:5 Comment(1)
This isn't SimpleAdapter.Extractor
P
10

My advice to you would be to create a separate class that extends the Adapter(or some subclass of it)

Here is a simple example of a String array adapter.

package ro.gebs.captoom.adapters;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import antistatic.spinnerwheel.adapters.AbstractWheelTextAdapter;

import com.example.captoom.R;

public class LanguagesAdapter extends AbstractWheelTextAdapter {
    // Countries names
    private String languages[];

    public LanguagesAdapter(Context context) {
        super(context, R.layout.lang_item, NO_RESOURCE);
        languages = context.getResources().getStringArray(R.array.lang_array);
        setItemTextResource(R.id.language_txt);
    }

    @Override
    public View getItem(int index, View cachedView, ViewGroup parent) {
        View view = super.getItem(index, cachedView, parent);
        return view;
    }

    @Override
    public int getItemsCount() {
        return languages.length;
    }

    @Override
    protected CharSequence getItemText(int index) {
        return languages[index];
    }
}

and the usage is simple just use the method .setAdapter();

Or another example which uses an arrayAdapter:

package apc.example;

import java.util.ArrayList;

import utils.BitmapManager;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class PersonAdapter extends ArrayAdapter<Person> {

    Context context;
    int layoutResourceId;
    ArrayList<Person> data = null;

    public PersonAdapter(Context context, int layoutResourceId,
            ArrayList<Person> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ItemHolder holder = null;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new ItemHolder();
            holder.imgIcon = (ImageView) row.findViewById(R.id.icon);
            holder.txtName = (TextView) row.findViewById(R.id.title);
            holder.txtDescription = (TextView) row.findViewById(R.id.desc);

            row.setTag(holder);
        } else {
            holder = (ItemHolder) row.getTag();
        }

        Person bean = data.get(position);
        holder.txtName.setText(bean.getName());
        holder.txtDescription.setText(bean.getDescription());


        Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.user);
        BitmapManager.INSTANCE.setPlaceholder(b);
        BitmapManager.INSTANCE.loadBitmap(bean.getUrl(), holder.imgIcon, 80, 80);

        return row;
    }

    public static class ItemHolder {
        public ImageView imgIcon;
        TextView txtName;
        TextView txtDescription;
    }

    public void updateAdapter(ArrayList<Person> pers){
        this.data = pers;
    }
}

This is an example of an adapter for a more complex class that has more fields rather than a simple string. But that can easily be modified to ArrayAdapter<String> and then go from there.

Anyways i think it's always a best practice to write your custom adapters for listviews.

Hope this helps!

Pareu answered 5/9, 2013 at 6:16 Comment(1)
+ 1 for custom adapter with ViewHolder Pattern! It's a valuable example.Intake
B
7

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);
Bagehot answered 5/9, 2013 at 7:5 Comment(1)
This isn't SimpleAdapter.Extractor
F
3

You're reusing the same view in your int[] object.

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

It looks like it's treating them all as the same object, so each time it adds a new item it changes the previous ones.

In order to use the SimpleAdapter you will need to define each view in the XML with different IDs.

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

The SimpleAdapter may be simpler in regard to it's internal complexity, but it's definitely not simpler to actually use. With an ArrayAdapter you can just pass it the list of items and let it generate views automatically. It can be any size you need it to be so long as you don't run out of memory. (See below for example)

Once you start working with custom adapters I highly recommend you watch Romain Guy & Adam Powell's I/O talk. It's all a lot to take in when learning, but they do a great job of explaining how ListViews work.

//List of Items
String[] name_of_bookmarks = { "php","c","android","hacking" };

//Create your List object for the ArrayAdapter
//and make it the same size as name_of_books
List<String> listBookmarks = new ArrayList<String>(Array.getLength(name_of_bookmarks));

//Add name_of_bookmarks contents to listBookmarks
Collections.addAll(listBookmarks, name_of_books);

//Create an ArrayAdapter passing it the Context, a generic list item and your list
//An alternative to "this" would be "getApplicationContext()" from your main activity
//or "getActivity()" from a fragment. "getBaseContext()" is not recommended.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_item_text, listBookmarks);

//Set the adapter to your ListView
final ListView listView = (ListView) findViewById(R.id.mylist);
listView.setAdapter(arrayAdapter);
Fanfare answered 5/9, 2013 at 6:13 Comment(7)
So what should i do?? @FanfareAndes
Use different textviews for each.Myriad
If you know how many you'll need you can just add them in the layout's XML. To generate them on the fly will give you a lot more flexibility but will complicate things quite a bit.Fanfare
I just want to show "php","c","android","hacking" in a listview.If it have 200 item then is it possible to create 200 textview??Andes
I don't believe so with a SimpleAdapterFanfare
A ListAdapter would be another option and possibly simpler, I'll update my example in a moment to show one.Fanfare
The example above should work well for you and could be condensed down to just three or four lines if you wanted to. Although I do agree with the others that creating custom adapters is often much easier to work with once you understand them. They are a major part of programming on Android so are definitely worth putting the effort into.Fanfare
K
0

Try this one

  public class MyFragment extends ListFragment{

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        List<HashMap<String, String>> list= new ArrayList<HashMap<String,String>>();

        for (int i = 0; i < name_of_bookmarks.length; i++) {

            HashMap<String, String> map= new HashMap<String, String>();
            map.put("key",  name_of_bookmarks[i]);
            list.add(map);
        }
        String[] from = { "key" };

        int[] to = { R.id.txt};

        SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), list, R.layout.list_layout, from, to);
        setListAdapter(adapter);

        return super.onCreateView(inflater, container, savedInstanceState);
    }

}
Kati answered 5/9, 2013 at 6:15 Comment(3)
text1 is a textview in the layout so that i can show the name in a textviewAndes
why should i take another textview as R.id.txt2Andes
I just want to show "php","c","android","hacking" in a list view. thats itAndes
R
-1

Whatever You Are Face Problem Exactly I Am Face Of The Problem Called "List View Display Last Position Of Data Of An Array..."

The Problem Is Generated With Hash Map

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

ArrayList<HashMap<String, String>> list_of_bookmarks = new ArrayList<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++)
        { 
          HashMap<String, String> b = new HashMap<String, String>();
          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);

Try Out This One If Any Doubt Created In Your Mind Then Ask Me Whatever Question Again Simply You Have To Declared Your Hash Map Inside Your For Loop ...

Using Hash Map Inside Your For Loop Variable 'b' Created Each & Every Time With Considered As An Different Object. And Then Simply Array List Display Different Object Of Hash Map.

You Are Using Same Object To Store Value Of Hash Map And That Variable Was Override With Same Name That's Why you Are Faced The Problem Thank You...

Robalo answered 13/7, 2017 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.