Getting Started with Android Development – Part 2

This is a blog post by iOS Tutorial Team member Ali Hafizji, an iOS and Android developer living in India. This tutorial is a continuation of Getting Started with Android Development, this site’s first foray into developing for a non-Apple platform! Check it out if you haven’t already. If you were following along last time, […] By Ray Wenderlich.

Leave a rating/review
Save for later
Share
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

Adding New Quotes

To add a new quote, you first need to create an options menu. An options menu is what the user sees after pressing the menu button in Android. All basic activity actions and navigation items should be placed in an options menu.

When the Android system creates an options menu for the first time, it calls your activity’s onCreateOptionsMenu method. So that’s what you’re going to override to create your menu.

Open the QuoteReader activity and make the following changes:

// Add to top of QuoteReaderActivity
private static int CREATE_QUOTE_ID = 1;

// Add new method to QuoteReaderActivity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(Menu.NONE, CREATE_QUOTE_ID, Menu.NONE, "Create new quote");
	return true;
}

The method returns a menu object. Notice that you’re adding an entry to the menu object. The add method takes the following arguments:

  • groupId: The group identifier that this item should be part of. Use this to group a number of options together. Since you have only one, use NONE.
  • itemId: The unique ID given to each item in the menu. You’re using a static int variable with value 1.
  • order: The order for the item.
  • title: The string used to show the title of the menu item.

Build and run. You should now see an options menu when you press the menu button.

Adding an options menu in Android

Now that you’ve got your options menu, you need to get the an event when the user taps the “Create new quote” menu item.

The Android system includes a callback called onOptionsItemSelected, used when a menu item is tapped. That’s what you’ll be using.

Add the following lines to the QuoteReader activity:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == CREATE_QUOTE_ID) {
        //create an entry into the data set
        //and call data set changed
        DataSource dataSource = DataSource.getDataSourceInstance(this);
        dataSource.getmItemsData().add(new DataSourceItem());
        QuoteAdapter adapter = (QuoteAdapter) mListView.getAdapter();
        adapter.notifyDataSetChanged();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

The code checks if the menu item you created has been tapped, and if so, creates a new quote. To add a new quote, you only need to create a new entry in your data source and tell the adapter that the data set has changed.

Build and run the project, and see if when you create a new quote, a new entry is created in the list with default values. Note you’ll have to scroll down to the bottom of the list to see the new entries.

Adding new entries onto a list in Android

Deleting Quotes

To delete a quote you’re going to use a context menu. Think of a context menu as the menu you see when you right-click on an item on any operating system. The menu you see contains options that are very specific to that one item: that’s a context menu.

In this case, your QuoteReader will show a context menu when the user long-presses on a particular item in the quotes list. The first step to implementation is registering the view that will show the context menu. To do this, add the following line of code to the onCreate method of the QuoteReader activity.

registerForContextMenu(mListView);

Now that your list is registered, whenever the user long-presses on an item in the list, the system will give a callback called onCreateContextMenu. Now you’ll override that method and add code to create the menu.

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);       
    menu.setHeaderTitle(getResources().getString(R.string.context_menu_title));
}

Note you’ll get an error because we haven’t added the string for the context_menu_title yet, so add this to your res\values\strings.xml file:

<string name="context_menu_title">Menu</string>

This time, instead of creating a menu using the add method, you’ll use XML. So create a new XML file in the res/layout directory and name it context_menu.xml. Here’s how the file should look:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/delete" android:title="Delete"/>
</menu>

You’ll use this XML file in your onCreateContextMenu and attach it to the menu object. Use the MenuInflator class to do this. Add the following lines to the end of the onCreateContextMenu method:

MenuInflater menuInflator = getMenuInflater();
menuInflator.inflate(R.layout.context_menu, menu);

Build and run. Now when you long-press on any list element, you should see the menu you just created.

Adding a context menu in Android

To capture the event when the user taps on your menu item, you need to override another function called onContextMenuItemSelected. The code below deletes the item from the data source and tells the adapter to refresh the list.

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
    if(item.getItemId() == R.id.delete) {
        DataSource.getDataSourceInstance(this).getmItemsData().remove(info.position);
        QuoteAdapter adapter = (QuoteAdapter) mListView.getAdapter();
        adapter.notifyDataSetChanged();
        return true;
    }
    return super.onContextItemSelected(item);
}

Give it a final build and run. You should now have a completely functional app with full editing, adding, and deleting support!

Where to Go From Here?

Here is an example project with all of the code from the above tutorial.

One thing I didn’t cover in this tutorial is how to edit the thumbnails. This might be a fun thing to try to add on your own if you want to play around with this some more!

Please let me know if you have any questions regarding that, or anything else in this tutorial. Also, please let me know if you’d like to see more Android tutorials on this site (and what you’d like them to cover if so!) :]

This is a blog post by iOS Tutorial Team member Ali Hafizji, an iOS and Android developer living in India.

Contributors

Over 300 content creators. Join our team.