Android - Store Class Object into ArrayList or List

In this tutorial, we will change our model to be a list of restaurants, rather than just one. Then, we will add a ListView to view the available restaurants.
This will be rather incomplete, in that we can only add a new restaurant, not edit or delete an existing one. We will cover those steps too in a later tutorial.

Note : Please refer previous post before step on this tutorial

Hold a List of Restaurants

First, if we are going to have a list of restaurants in the UI, we need a list of restaurants as our model. So, in LunchList, change:

Restaurant r=new Restaurant();

to

List<Restaurant> model=new ArrayList<Restaurant>();

Note that you will need to import java.util.List and java.util.ArrayList as well.

Save Restaurant Object to List

All we need to do is add a local restaurant r variable, populate it, and add it to the list:

private View.OnClickListener onSave=new View.OnClickListener() {
          public void onClick(View v) {
                     Restaurant r=new Restaurant();
                     EditText name=(EditText)findViewById(R.id.name);
                     EditText address=(EditText)findViewById(R.id.addr);
                     r.setName(name.getText().toString());
                     r.setAddress(address.getText().toString());
                     RadioGroup types=(RadioGroup)findViewById(R.id.types);
                     switch (types.getCheckedRadioButtonId()) {
                              case R.id.sit_down:
                                      r.setType("sit_down");break;
                              case R.id.take_out:
                                      r.setType("take_out");break;
                              case R.id.delivery:
                                      r.setType("delivery");break;
                      }
            }
};


Implement toString()

To simplify the creation of our ListView, we need to have our restaurant class respond intelligently to toString(). That will be called on each restaurant as it is displayed in our list.

For the purposes of this tutorial, we will simply use the name. So, add a toString() implementation on restaurant like this:


public String toString() {
       return(getName());
}


Add a ListView Widget

This is the challenging part ---> adding the ListView to the layout.

The challenge is in getting the layout right. Right now, while we have only the one screen to work with, we need to somehow squeeze in the list without eliminating space for anything else. In fact, ideally, the list takes up all the available space that is not being used by our current detail form.

One way to achieve that is to use a RelativeLayout as the over-arching layout for the screen. We anchor the detail form to the bottom of the screen, then have the list span the space from the top of the screen to the top of the detail form.

To make this change, replace your current LunchList/res/layout/main.xml with the following:


<?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="fill_parent"
>
<TableLayout android:id="@+id/details"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:stretchColumns="1"
>
<TableRow>
<TextView android:text="Name:" />
<EditText android:id="@+id/name" />
</TableRow>
<TableRow>
<TextView android:text="Address:" />
<EditText android:id="@+id/addr" />
</TableRow>
<TableRow>
<TextView android:text="Type:" />
<RadioGroup android:id="@+id/types">
<RadioButton android:id="@+id/take_out"
android:text="Take-Out"
/>
<RadioButton android:id="@+id/sit_down"
android:text="Sit-Down"
/>
<RadioButton android:id="@+id/delivery"
android:text="Delivery"
/>
</RadioGroup>
</TableRow>
<Button android:id="@+id/save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
/>
</TableLayout>
<ListView android:id="@+id/restaurants"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_above="@id/details"
/>
</RelativeLayout>


If you recompile and rebuild the application, then run it, you will see our form slid to the bottom, with empty space at the top:

Build and Attach the Adapter

The ListView will remain empty, of course, until we do something to populate it. What we want is for the list to show our running lineup of restaurant objects.

Since we have our ArrayList<Restaurant>, we can easily wrap it in an ArrayAdapter<Restaurant> . This also means, though, that when we add a restaurant, we need to add it to the ArrayAdapter via add(). The adapter  will, in turn, put it in the ArrayList. Otherwise, if we add it straight to the ArrayList, the adapter will not know about the added restaurant and
therefore will not display it.

Here is the new implementation of the LunchList class:

package apt.tutorial;


import android.app.Activity;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import java.util.ArrayList;
import java.util.List;


public class LunchList extends Activity {
            List<Restaurant> model=new ArrayList<Restaurant>();
            ArrayAdapter<Restaurant> adapter=null;


            @Override
            public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
                    Button save=(Button)findViewById(R.id.save);
                    save.setOnClickListener(onSave);
                    ListView list=(ListView)findViewById(R.id.restaurants);
                    adapter=new ArrayAdapter<Restaurant>(this,
                    android.R.layout.simple_list_item_1,model);
                    list.setAdapter(adapter);
           }
           private View.OnClickListener onSave=new View.OnClickListener() {
                    public void onClick(View v) {
                             Restaurant r=new Restaurant();
                             EditText name=(EditText)findViewById(R.id.name);
                             EditText address=(EditText)findViewById(R.id.addr);
                             r.setName(name.getText().toString());
                             r.setAddress(address.getText().toString());
                             RadioGroup types=(RadioGroup)findViewById(R.id.types);
                             switch (types.getCheckedRadioButtonId()) {
                                    case R.id.sit_down:
                                            r.setType("sit_down");break;
                                    case R.id.take_out:
                                            r.setType("take_out");break;
                                    case R.id.delivery:
                                            r.setType("delivery");break;

                            }
                            adapter.add(r);
                   }
          };
}


The magic value android.R.layout.simple_list_item_1 is a stock layout for a list row, just displaying the text of the object in white on a black background with a reasonably large font. In later tutorials, we will change the look of our rows to suit our own designs.

If you then add a few restaurants via the form, it will look something like this:




By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

Phone book application example - Java

Modal Popup Message Box ASP.NEt C# Example