Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Android - To DoShopping List

5.00/5 (2 votes)
13 Jun 2013CPOL4 min read 37.6K  
This tip explains how to create a to do or Shopping List app with listview, sqlite, dialog and customadapter

Introduction

This tip shows how a Shopping\To do list application is created. It gives an idea of the following:

  1. Adding a list Item in an Activity
  2. Opening Dialog from Android Activity
  3. Working with SQlite
  4. How to return data from one activity to another

to do list

In this tip, we will be discussing about the first 2 points.

The Beginning

This tip assumes that you are aware of how an Android project is created. Create a new Android Project with the following details:

  • Application Name = UtilityPlus Project Name = UtilityPlus Package Name = com.utility.utilityplus
  • Minimum Required SDK & Target SDK = API 11 Android 3.0 (HoneyComb) and Click Finish.

Activities & Resources

This application contains the following major components:

  1. MainActivity - Displaying the list of existing Shopping\To do List
  2. Dialog - A pop-up asking for the name of list from user
  3. Add new Data Activity - User would enter the content of list here.
  4. Adapter - For display of Data in MainActivity
  5. DatabaseHelper - For connecting and communicating with MainApplication

Using the Code

Adding a List Item in an Activity

Before moving on, we need to understand a few basic concepts, which are being used here:

  • ListView - Displays a scrollable list of logically related items. It's an important UI Component and is used in many apps for various purposes.
  • ListView Item - The items\data being displayed in a single row. It can be plain text(e.g. displaying the names of your contacts) or it can be much more complicated with 2 EditText for name and number, 2 buttons for edit and delete.
  • Data Source - The web definition of DataSources say: "The people, documents, products, activities, events and records from which data are obtained." [Reference: http://www.evaluationtoolkit.org/glossary]
    With respect to coding, it can be an ArrayList, Array of any data-type (basic or complex)
  • Adapter - A piece of code which takes data from a data-source and makes it compatible to the ListView.
    In practical, the relationship between ListView and its adapter is much more complicated.

Display Plain Text as a List Item in the ListView

  1. Add ListView in the resource layout XML
  2. Create\find a Data Source
  3. Create an Adapter for a Data Source
  4. Assign Adapter to the ListView

It's done!

The ListView can be dragged from the left pane of the graphical display of the Resource XML or the below code can be copied in the XML view:

XML
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" 
>
</ListView>

Data Source: Here, we are taking an Array of String:

Java
String[] strNoData = { "Item1", "Item2", "Item3" };//DataSource

Adapter: We are using simple arrayAdapter and then set adapter in the listview using setAdapter.

Java
ArrayAdapter<string> objAdapter = new ArrayAdapter<string>(this,
        android.R.layout.simple_list_item_1, android.R.id.text1,
        strDataSource);
listview.setAdapter(objAdapter);</string> </string> 

Display Set of Controls as a List Item in the ListView

Steps
  1. Add ListView in the resource layout XML
  2. Create\find a Data Source
  3. Create an XML layout resource for the row template in ListView
  4. Create an Adapter for a Data Source
  5. Assign Adapter to the ListView

It's done !!!

XML layout resource for the row template in ListView. The below template would be used for all the rows in the ListView.

XML
<LinearLayout ...
    <FrameLayout  ...
    <TextView android:id="@+id/textView_datetime"           
    android:layout_width="wrap_content" android:layout_height="wrap_content" 
    android:text="" android:textAppearance="?android:attr/textAppearanceMedium" 
    android:layout_gravity="left"/>
    <Button android:id="@+id/button_Edit" android:layout_width="wrap_content" 
    android:layout_height="wrap_content" android:text="@+string/str_edit" 
    android:onClick="onClick" android:layout_gravity="center_horizontal"/>
    <Button android:id="@+id/button_delete" android:layout_height="wrap_content" 
    android:layout_width="wrap_content" android:text="@+string/str_delete" 
    android:layout_gravity="right" android:onClick="onClick"/>
    </FrameLayout>
    <TextView android:id="@+id/textView_notename" android:layout_width="wrap_content" 
    android:layout_height="wrap_content" android:text="" 
    android:textAppearance="?android:attr/textAppearanceMedium" 
    android:gravity="bottom"/>
</LinearLayout> 

Creating a Custom Adapter

We can extend any adapter class provided by Android and can create our own custom adapter. Here, we would be using ArrayAdapter class. In the adapters, we need to override getView method. This method would return the view of single row. See the code below:

Java
@Override
public View getView(int position, View convertView, ViewGroup parent) {        
    LayoutInflater vi = (LayoutInflater) 
    getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = vi.inflate(R.layout.showlistrow, null);
    
    ShowData showData = m_ListItems.get(position);
    
    if (showData != null) {
        try {
            //Write code to display the controls in the layout XML
        } catch (Exception ex) {
            ...
        }
    }
    return convertView;
}  

Now, the above code is correct but we can optimize it further. We can reuse the Views of ListItems which are not visible on the screen.
Let's suppose, 5 Listitems can be displayed on the screen. We would create new view for each item. Right now, there are 5 views in the memory.
When we scroll down our listitem, the first ListItem is not being displayed and 6th comes in the view. So, instead of creating a new view for the 6th item , we can reuse the first items view. Creating a new view in Android is expensive Just add a check for existing view.

Java
@Override
public View getView(int position, View convertView, ViewGroup parent) {        
    if(convertView!=null) { //Check added for optimizing the code.
        LayoutInflater vi = (LayoutInflater) 
        getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = vi.inflate(R.layout.showlistrow, null);
        
        ShowData showData = m_ListItems.get(position);
        
        if (showData != null) {
            try {
                //Write code to display the controls in the layout xml
            } catch (Exception ex) {
                ...
            }
        }
        return convertView;
    } 

Assign adapter to ListView:

Java
ShowDataAdapter adapter_Data = new ShowDataAdapter
(this,android.R.layout.simple_list_item_1, android.R.id.text1,list_AdapterItems);
listview.setAdapter(adapter_Data);

Opening Dialog from Android Activity

This can be achieved in 2 ways:

  • Via AlertDialog
  • Via Dialog Class

Via AlertDialog

  1. Declare AlertDialog object
  2. Set Message and Title
  3. Set Positive and Negative Buttons
  4. Show Dialog
Java
AlertDialog alertDialog = new AlertDialog.Builder(Main.this).create();
alertDialog.setTitle("Error...");
alertDialog.setMessage("Unable to open. Continue?");
alertDialog.setPositiveButton(/*Create new onclickListener*/);
alertDialog.setNegativeButton(/*Create new onclickListener*/);
alertDialog.show();

Via Dialog Class

Steps
  1. Create an XML Resource for Dialog Layout.
  2. Derive a class from android.app.Dialog class of Android.

In the XML Resource, add all the controls that we want to display in our Dialog. Here, we would be adding a TextView and OK, Cancel buttons.
In the constructor of derive class, set XML Resource by calling setContentView().

Java
setContentView(R.layout.popup);

Revision History

  • 9th June 2013: Initial release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)