Android Development 13

Android Development TutorialWelcome to part 13 of my Android Development Tutorial! In this tutorial I will continue building the Android Address Book App previously covered in parts 10, 11 and 12. If you haven’t seen them, check them out first.

Specifically in this tutorial I will create the Java that will power the ListView for the Main Activity and I’ll also cover the New Contact code needed to add a contact to the database. All of the heavily commented code after the video should help make everything understandable.

If you like videos like this, it helps to tell Google+ with a click here [googleplusone]

Code From the Video

package com.newthinktank.contactsapp;

import java.util.ArrayList;
import java.util.HashMap;

import com.newthinktank.contactsapp.DBTools;
import com.newthinktank.contactsapp.NewContact;

import android.os.Bundle;
import android.content.Intent;

import android.view.View;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.ListView;

public class MainActivity extends ListActivity {

	// The Intent is used to issue that an operation should
	// be performed

	Intent intent;
	TextView contactId;

	// The object that allows me to manipulate the database

	DBTools dbTools = new DBTools(this);

	// Called when the Activity is first called

	protected void onCreate(Bundle savedInstanceState) {
		// Get saved data if there is any


		// Designate that activity_main.xml is the interface used

		// Gets all the data from the database and stores it
		// in an ArrayList

		ArrayList<HashMap<String, String>> contactList =  dbTools.getAllContacts();

		// Check to make sure there are contacts to display

		if(contactList.size()!=0) {
			// Get the ListView and assign an event handler to it
			ListView listView = getListView();
			listView.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					// When an item is clicked get the TextView
					// with a matching checkId
					contactId = (TextView) view.findViewById(;
					// Convert that contactId into a String
					String contactIdValue = contactId.getText().toString();	
					// Signals an intention to do something
					// getApplication() returns the application that owns
					// this activity
					Intent  theIndent = new Intent(getApplication(),EditContact.class);
					// Put additional data in for EditContact to use
					theIndent.putExtra("contactId", contactIdValue); 
					// Calls for EditContact
			// A list adapter is used bridge between a ListView and
			// the ListViews data
			// The SimpleAdapter connects the data in an ArrayList
			// to the XML file
			// First we pass in a Context to provide information needed
			// about the application
			// The ArrayList of data is next followed by the xml resource
			// Then we have the names of the data in String format and
			// their specific resource ids
			ListAdapter adapter = new SimpleAdapter( MainActivity.this,contactList, R.layout.contact_entry, new String[] { "contactId","lastName", "firstName"}, new int[] {,,});
			// setListAdapter provides the Cursor for the ListView
			// The Cursor provides access to the database data
	// When showAddContact is called with a click the Activity 
	// NewContact is called
	public void showAddContact(View view) {
		Intent theIntent = new Intent(getApplication(), NewContact.class);

package com.newthinktank.contactsapp;

import java.util.HashMap;

import android.content.Intent;
import android.os.Bundle;

import android.view.View;

import android.widget.EditText;

public class NewContact extends Activity{

	// The EditText objects

	EditText firstName;
	EditText lastName;
	EditText phoneNumber;
	EditText emailAddress;
	EditText homeAddress;

	DBTools dbTools = new DBTools(this);

	public void onCreate(Bundle savedInstanceState) {

		// Get saved data if there is any


		// Designate that add_new_contact.xml is the interface used

		// Initialize the EditText objects
		firstName = (EditText) findViewById(;
		lastName = (EditText) findViewById(;
		phoneNumber = (EditText) findViewById(;
		emailAddress = (EditText) findViewById(;
		homeAddress = (EditText) findViewById(;

	public void addNewContact(View view) {
		// Will hold the HashMap of values 
		HashMap<String, String> queryValuesMap =  new  HashMap<String, String>();

		// Get the values from the EditText boxes
		queryValuesMap.put("firstName", firstName.getText().toString());
		queryValuesMap.put("lastName", lastName.getText().toString());
		queryValuesMap.put("phoneNumber", phoneNumber.getText().toString());
		queryValuesMap.put("emailAddress", emailAddress.getText().toString());
		queryValuesMap.put("homeAddress", homeAddress.getText().toString());

		// Call for the HashMap to be added to the database
		// Call for MainActivity to execute
	public void callMainActivity(View view) {
		Intent theIntent = new Intent(getApplication(), MainActivity.class);

26 Responses to “Android Development 13”

  1. Josh Janvrin says:

    Derek, thank you so much for all of these tutorials. By far the clearest available. If I wanted to also include an ImageView in the list layout, say, a contact photo, and I was storing these pngs in a drawable folder, how would I alter the adapter?

    I was thinking of having a column in the database which contained a string of the filename. Now just to connect it…

    • Derek Banas says:

      You’re very welcome 🙂 I’ll cover adding video, images, animations, etc. as soon as possible. My next Android video will be on fragments and nice interfaces. I’ll get it up as soon as possible

  2. Ashish S. says:

    Best tutorial in android available in hundreds of tutorial in Youtube . I am new in android but just watching tutorials and code i am now able to start code in JUST 3 Days ..

  3. TT says:

    Hi Derek,

    What if my table has multiple datatypes? How would the hashmap be different then? FOr e.g. my table has INTEGER AND TEXT fields that I need to insert to db. Can you please advise?


  4. lorlo says:

    I run StockQuotes no problem with my Bionic device but I cannot get the to run. Would you see inside my logCat and direct me to fix? Thx in advance.

    09-09 10:17:54.608: E/Trace(22126): error opening trace file: No such file or directory (2)
    09-09 10:17:54.694: E/AndroidRuntime(22126): FATAL EXCEPTION: main
    09-09 10:17:54.694: E/AndroidRuntime(22126): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.theratutoring.contactsapp/com.theratutoring.contactsapp.MainActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is ‘’
    09-09 10:17:54.694: E/AndroidRuntime(22126): at
    09-09 10:17:54.694: E/AndroidRuntime(22126): at
    09-09 10:17:54.694: E/AndroidRuntime(22126): at$700(
    09-09 10:17:54.694: E/AndroidRuntime(22126): at$H.handleMessage(
    09-09 10:17:54.694: E/AndroidRuntime(22126): at android.os.Handler.dispatchMessage(
    09-09 10:17:54.694: E/AndroidRuntime(22126): at android.os.Looper.loop(
    09-09 10:17:54.694: E/AndroidRuntime(22126): at
    09-09 10:17:54.694: E/AndroidRuntime(22126): at java.lang.reflect.Method.invokeNative(Native Method)
    09-09 10:17:54.694: E/AndroidRuntime(22126): at java.lang.reflect.Method.invoke(
    09-09 10:17:54.694: E/AndroidRuntime(22126): at$
    09-09 10:17:54.694: E/AndroidRuntime(22126): at
    09-09 10:17:54.694: E/AndroidRuntime(22126): at dalvik.system.NativeStart.main(Native Method)
    09-09 10:17:54.694: E/AndroidRuntime(22126): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is ‘’
    09-09 10:17:54.694: E/AndroidRuntime(22126): at
    09-09 10:17:54.694: E/AndroidRuntime(22126): at
    09-09 10:17:54.694: E/AndroidRuntime(22126): at
    09-09 10:17:54.694: E/AndroidRuntime(22126): at com.theratutoring.contactsapp.MainActivity.onCreate(
    09-09 10:17:54.694: E/AndroidRuntime(22126): at
    09-09 10:17:54.694: E/AndroidRuntime(22126): at
    09-09 10:17:54.694: E/AndroidRuntime(22126): at
    09-09 10:17:54.694: E/AndroidRuntime(22126): … 11 more

    • lorlo says:

      Is it merely adding the list to R and if yes, what is best approach?

      • Derek Banas says:

        It looks like the R file isn’t auto updating. Make sure you don’t have any import R imports in any of your java files in src. If you do delete them and then restart Eclipse. You may also want to check for Updates (Help -> Check for Updates)

    • Anonymous says:

      hello there, I am also running into the same problem. My application failed to start. Please share if you got it solved. Thanks

    • Dinho says:

      hello there, I was also running into the same kind of error, only that my app wont even start at all. But it throws the same log errors as yours. Please kindly help if you have found the solution to it. Thanks

  5. My opinion is that when you populate a list with data from a SQLite database, the simplest is to extend a cursor adapter, with bindView and NewView, in bindView you don’t need to care for recycling of layout inflation…

  6. bilgoude says:

    hi Banas there’s problem with setListAdapter. Could you please help me with this problem. Thanks

  7. Han says:

    Hello. I have recently started to learn android development (and programming in general) and your guide series helped me a lot.

    Right now I am trying to create a endless listview (listview expands as you scroll down to avoid load time) for a large set of data. After some research, I gathered that I should use a CursorAdapter and extends commonware’s endlessadapter.

    Am I on the right track? I am not expecting a long answer, but I just don’t want to spent a lot of time looking for the wrong thing 🙂

    Helpfully you see this, and thank you!

  8. Mhd Oda says:

    Hello Derek,
    Firstly, I want to thank for this great tutorials,
    Secondly, I have problem I am copy your code of mainActivity and activity_main.xml but in the catlog the following error arise:
    12-04 22:29:45.982: E/AndroidRuntime(2462): cannot open customer xml file
    and when I make a debugging the run stop at this line of code

    Please I need Your Help.

  9. Miguel says:

    Hi Derek!
    Just wanted to start off by saying great tutorials and am so grateful for the time you take to make them and also answer questions.
    I have a question for you, I’ve googled and googled and searched and haven’t been able to find an answer.
    I’m designing and app that has a stopwatch aspect to it. Now my question is regarding storing the values of the splits.
    I.e. I don’t know how many splits a user needs because it varies from race to race.
    I’ve thought of 2 solutions:
    1. make 100 columns and hope the user doesn’t need more than 98 splits/race. (although I think this would make it too bulky esp. if they only need 1 or 2 splits).
    2. make 2 tables and reference the second table splits. 1 with (|id|finaltime|splitsrefnum|) and the other with (|split|) so if it had 5 splits, it would have 5 rows. etc…

    I believe #2 is foreignkeys?

    You don’t need waste your time and write code, I’d just appreciate a push in the right direction so I could know what the “right way” of doing this is.

    Thanks again!

    • Derek Banas says:

      Hi Miguel,

      Why not save the data to a file and then you won’t need to worry about defining a maximum size. Anytime I need to store a ton of information and I want to keep it organized I use SQLite. I have tutorials on both on my site. I hope that helps 🙂

  10. Ahmed Ali says:

    hi Derek, thank you for your great effort,
    and i have a little question, i wanna make my first android app 🙂 and i have a small idea i wanna make “Taking Notes app” just to apply what i learned from you, but i have no idea about what my app should looks like, and if you have any idea what the app should looks like plz tell me and i will be grateful to you, thank you in advance and thank you for your great effort again 🙂

    • Derek Banas says:

      Thank you 🙂 I’m going to be making more Java Android videos very soon. I’ll cover everything I didn’t cover before. I’ll spend a lot of time on interfaces.

  11. lml says:

    hi, thanks for ur tutorial…
    but can i know how to add a dialog box and show the details confirmation whether to save or cancel before save.?


Leave a Reply

Your email address will not be published.