Search code examples
javaandroidlistviewonclickandroid-arrayadapter

Accessing listview/arrayadapter from within button OnClick method


This may be a bit of a silly question, but I am having a bit of a hard time understanding how to reference a listview/adapter that I created. I started by creating a custom listview that will allow me to display list items that have both pictures and text in them. I found a lot of great tutorials online, so this part wasn't too bad. I then added two buttons at the bottom of the listview that I would like to use to manipulate data within the listview. Now I can figure out how to access the list when I am in the onItemClickListener for the list, because you can simply call parent.getItemAtPosition(position) in order to access it. I am not quite sure how to access this list within the onClick method for the button, since the parent/position are not passed as parameters. So I suppose my first question is...

  1. How to properly access the listview/arrayadapter I created from within my button onClick method.

The other question that I have been struggling with is how to search for an item (row) in my listview by searching for the value of a specific element withing that row. For instance, in my code below, the rows I have created have five images, two text fields, and a boolean value. So how would I go about searching through my list to find the row that has the "address" of 555555, which corresponds to the Harley Davidson list entry.

I have included my code below. Thank you very much for the help.

HelmetList.java

public class HelmetList
{
    public HelmetList (String name, String address, String img_hel, String img_rec, String img_bat,
                            String img_dsk, String img_str, Boolean selected)
    {
        super();
        this.name       = name;
        this.address    = address;
        this.img_hel    = img_hel;
        this.img_rec    = img_rec;
        this.img_bat    = img_bat;
        this.img_dsk    = img_dsk;
        this.img_str    = img_str;
        this.selected   = selected;
    }

    private String name;
    private String address;
    private String img_hel;
    private String img_rec;
    private String img_bat;
    private String img_dsk;
    private String img_str;
    private Boolean selected;

    public String getName ()
    {
        return name;
    }

    public void setName (String s_name)
    {
        this.name = s_name;
    }

    public String getAddress ()
    {
        return address;
    }

    public void setAddress (String s_address)
    {
        this.address = s_address;
    }

    public String getImgHel ()
    {
        return img_hel;
    }

    public void setImgHel (String s_img_hel)
    {
        this.img_hel = s_img_hel;
    }

    public String getImgRec ()
    {
        return img_rec;
    }

    public void setImgRec (String s_img_rec)
    {
        this.img_rec = s_img_rec;
    }

    public String getImgBat ()
    {
        return img_bat;
    }

    public void setImgBat (String s_img_bat)
    {
        this.img_bat = s_img_bat;
    }

    public String getImgDsk ()
    {
        return img_dsk;
    }

    public void setImgDsk (String s_img_dsk)
    {
        this.img_dsk = s_img_dsk;
    }

    public String getImgStr ()
    {
        return img_str;
    }

    public void setImgStr (String s_img_str)
    {
        this.img_str = s_img_str;
    }

    public Boolean getSelected ()
    {
        return selected;
    }

    public void setSelected (Boolean s_selected)
    {
        this.selected = s_selected;
    }
}

HelmetListAdapter.java

public class HelmetListAdapter extends ArrayAdapter<HelmetList>
{
    private int resource;
    private LayoutInflater inflater;
    private Context context;

    public HelmetListAdapter (Context p_context, int p_resource, List<HelmetList> p_objects)
    {
        super (p_context, p_resource, p_objects);
        resource = p_resource;
        inflater = LayoutInflater.from (p_context);
        context = p_context;
    }

    @Override
    public View getView (int position, View convertView, ViewGroup parent)
    {
        convertView = ( RelativeLayout ) inflater.inflate( resource, null );
        HelmetList Helmet = getItem (position);

        TextView hname = (TextView) convertView.findViewById(R.id.h_name);
        hname.setText(Helmet.getName ());

        TextView haddress = (TextView) convertView.findViewById(R.id.h_address);
        haddress.setText(Helmet.getAddress ());

        ImageView himage = (ImageView) convertView.findViewById(R.id.h_image);
        String uri = "drawable/" + Helmet.getImgHel();
        int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
        Drawable image = context.getResources().getDrawable(imageResource);
        himage.setImageDrawable(image);

        ImageView hrec = (ImageView) convertView.findViewById(R.id.h_rec);
        uri = "drawable/" + Helmet.getImgRec();
        imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
        image = context.getResources().getDrawable(imageResource);
        hrec.setImageDrawable(image);

        ImageView hlbat = (ImageView) convertView.findViewById(R.id.h_lb);
        uri = "drawable/" + Helmet.getImgBat();
        imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
        image = context.getResources().getDrawable(imageResource);
        hlbat.setImageDrawable(image);

        ImageView hldsk = (ImageView) convertView.findViewById(R.id.h_ld);
        uri = "drawable/" + Helmet.getImgDsk();
        imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
        image = context.getResources().getDrawable(imageResource);
        hldsk.setImageDrawable(image);

        ImageView hstr = (ImageView) convertView.findViewById(R.id.h_str);
        uri = "drawable/" + Helmet.getImgStr();
        imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
        image = context.getResources().getDrawable(imageResource);
        hstr.setImageDrawable(image);

        return convertView;

    }
}

MainActivity.java

public class MainActivity extends Activity
{
    private ListView lvhelmets;
    private HelmetListAdapter adhelmets;
    private Context ctx;
    List<Integer> selected;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ctx = this;

        List<HelmetList> helmetlist = new ArrayList<HelmetList>();
        helmetlist.add(new HelmetList("Bell", "11111", "helmetpic0", "rec",
                "bat", "mm", "str", Boolean.FALSE));
        helmetlist.add(new HelmetList("Shoei", "33333", "helmetpic1", "rec",
                                        "bat", "mm", "str", Boolean.FALSE));
        helmetlist.add(new HelmetList("Harley Davidson", "55555", "helmetpic2", "rec",
                                        "bat", "mm", "str", Boolean.FALSE));
        helmetlist.add(new HelmetList("Joe Rocket", "77777", "helmetpic3", "rec",
                "bat", "mm", "str", Boolean.FALSE));


        lvhelmets = (ListView) findViewById(R.id.Helmet_list);
        lvhelmets.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);

        adhelmets = new HelmetListAdapter(ctx, R.layout.row_format, helmetlist);
        lvhelmets.setAdapter (adhelmets);

        Button price = (Button) findViewById(R.id.bPrice);
        Button safety = (Button) findViewById(R.id.bSafety);

        price.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Toast.makeText(MainActivity.this, "price", Toast.LENGTH_SHORT).show();
            }
        });

        safety.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Toast.makeText(MainActivity.this, "safety", Toast.LENGTH_SHORT).show();
            }
        });



        lvhelmets.setOnItemClickListener(new OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                HelmetList helmet = (HelmetList) parent.getItemAtPosition(position);

                if (!helmet.getSelected())
                {
                    view.setBackgroundColor(Color.LTGRAY);
                    helmet.setSelected(Boolean.TRUE);
                }
                else
                {
                    view.setBackgroundColor(Color.TRANSPARENT);
                    helmet.setSelected(Boolean.FALSE);
                }
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

activity_main.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="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/Helmet_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:paddingTop="5dp"
        android:choiceMode="multipleChoice"
        android:layout_weight="1">
    </ListView>

    <LinearLayout
        android:id="@+id/btnHolderLL"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/bPrice"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingRight="1dp"
            android:paddingLeft="1dp"
            android:textColor="#FFFFFF"
            android:background="#222222"
            android:text="Price"
            android:clickable="true" />

        <Button
            android:id="@+id/bSafety"
            android:layout_width="1dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingRight="1dp"
            android:paddingLeft="1dp"
            android:textColor="#FFFFFF"
            android:background="#222222"
            android:text="Safety"
            android:clickable="true" />
    </LinearLayout>

</LinearLayout>

row_format.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dip" >

    <!--  ListRow Left side Thumbnail image -->
    <LinearLayout android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="3dip"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="5dip">
        <ImageView
            android:id="@+id/h_image"
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:layout_marginLeft="5dip"/>
    </LinearLayout>

    <TextView
        android:id="@+id/h_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:textColor="#040404"
        android:typeface="sans"
        android:textSize="20dip"
        android:layout_marginTop="5dip"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/h_address"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/h_name"
        android:textColor="#343434"
        android:textSize="12dip"
        android:layout_marginTop="1dip"
        android:layout_toRightOf="@+id/thumbnail"  />

    <ImageView
        android:id="@+id/h_rec"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="5dp"
        android:layout_centerVertical="true" />

    <ImageView
        android:id="@+id/h_lb"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="45dp"
        android:layout_centerVertical="true" />

    <ImageView
        android:id="@+id/h_ld"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="85dp"
        android:layout_centerVertical="true" />

    <ImageView
        android:id="@+id/h_str"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="125dp"
        android:layout_centerVertical="true" />
</RelativeLayout>

Solution

  • In the onClick method, try:

    lvhelmets.setAdapter(new HelmetListAdapter(ctx, rowf_format.xml, helmetList));
    

    That will call your adapter which will populate the listview.