Tutorial details

Android beginner tutorial: Part 71 - Adding contacts to the database | App Code for Sale | Preview

Android beginner tutorial: Part 71 - Adding contacts to the database | Android Tutorial

How to add new contacts to the database and update the list in our application

Overview PAGE TOP

In this tutorial we'll add the ability to add new contacts to the database and update the list in our application.

We are going to add a menu item that launches a dialog window, which lets us add a new record to the table.

First of all, let's create a layout xml for the dialog window. It shuold include 2 EditText objects - set their ids to inpname and inpphone and set their inputTypes to textPersonName and phone.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <EditText
        android:id="@+id/inp_name"
        android:inputType="textPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="4dp"
        android:hint="Name" />
    <EditText
        android:id="@+id/inp_phone"
        android:inputType="phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="16dp"
        android:fontFamily="sans-serif"
        android:hint="Phone"/>
</LinearLayout>

Now return to MainActivity.java class.

Take the code that loads data from the database to update the ListView's contents and turn it into a function:

public void updateList(){
String[] columns = new String[] {myDbHelper._ID, myDbHelper.NAME, myDbHelper.PHONE};
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(CONTENT_URI, columns, null, null, null);

final ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.customrow, cursor, new String[] {myDbHelper.NAME, myDbHelper.PHONE}, new int[] {R.id.t_name, R.id.t_phone}, 0);
Toast.makeText(this, "Rows found: " + adapter.getCount(), Toast.LENGTH_SHORT).show();
ListView list = (ListView)findViewById(R.id.contactList);
list.setAdapter(adapter);
}

Now declare an ID for the Add button in the options:

private static final int IDM_ADD = 101;

Now declare 2 variables for the dialog that we're going to create. The variables are AlertDialog and View class instances:

private AlertDialog addDialog;
private View alertView;

Create a onCreateOptionsMenu() function and add an "Add" item to the menu in it:

@Override
public boolean onCreateOptionsMenu(Menu menu){
menu.add(Menu.NONE, IDM_ADD, Menu.NONE, "Add");
return(super.onCreateOptionsMenu(menu));
}

When the item is selected, call a function called dialogAdd():

@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case IDM_ADD:
dialogAdd();
break;
}
return(super.onOptionsItemSelected(item));
}

Now go to the onCreate() function. Firstly we call the updateList() method to load the data:

// Load from database

updateList();

Then we create the dialog window using an AlertDialog.Builder object and add a click listener to its "OK" button. When the button is pressed, we Toast the values written by the user (for debugging reasons), and then insert() it into the database using the ContentResolver object:

// Create "Add contact" dialog

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
alertView = inflater.inflate(R.layout.add_window, null);
builder.setView(alertView);

builder.setTitle("Add contact");

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
EditText t_name = (EditText)alertView.findViewById(R.id.inp_name);
EditText t_phone = (EditText)alertView.findViewById(R.id.inp_phone);
String new_name = t_name.getText().toString();
String new_phone = t_phone.getText().toString();
Toast toast = Toast.makeText(getApplicationContext(), "Name: " + new_name + ", Phone: " + new_phone, Toast.LENGTH_SHORT);
toast.show();
ContentValues values = new ContentValues();
values.put(myDbHelper.NAME, new_name);
values.put(myDbHelper.PHONE, new_phone);
getContentResolver().insert(CONTENT_URI, values);
updateList();
}
});

builder.setCancelable(true);
addDialog = builder.create();

Full code looks like this:

package com.kircode.codeforfood_test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity{

private static final Uri CONTENT_URI = Uri.parse("content://com.kircode.codeforfood_test.mycontentprovider/contacts");
private static final int IDM_ADD = 101;

private AlertDialog addDialog;
private View alertView;

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

// Load from database

updateList();

// Create "Add contact" dialog

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
alertView = inflater.inflate(R.layout.add_window, null);
builder.setView(alertView);

builder.setTitle("Add contact");

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
EditText t_name = (EditText)alertView.findViewById(R.id.inp_name);
EditText t_phone = (EditText)alertView.findViewById(R.id.inp_phone);
String new_name = t_name.getText().toString();
String new_phone = t_phone.getText().toString();
Toast toast = Toast.makeText(getApplicationContext(), "Name: " + new_name + ", Phone: " + new_phone, Toast.LENGTH_SHORT);
toast.show();
ContentValues values = new ContentValues();
values.put(myDbHelper.NAME, new_name);
values.put(myDbHelper.PHONE, new_phone);
getContentResolver().insert(CONTENT_URI, values);
updateList();
}
});

builder.setCancelable(true);
addDialog = builder.create();
}

@Override
public boolean onCreateOptionsMenu(Menu menu){
menu.add(Menu.NONE, IDM_ADD, Menu.NONE, "Add");
return(super.onCreateOptionsMenu(menu));
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case IDM_ADD:
dialogAdd();
break;
}
return(super.onOptionsItemSelected(item));
}

public void dialogAdd(){
addDialog.show();
}

public void updateList(){
String[] columns = new String[] {myDbHelper._ID, myDbHelper.NAME, myDbHelper.PHONE};
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(CONTENT_URI, columns, null, null, null);

final ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.customrow, cursor, new String[] {myDbHelper.NAME, myDbHelper.PHONE}, new int[] {R.id.t_name, R.id.t_phone}, 0);
Toast.makeText(this, "Rows found: " + adapter.getCount(), Toast.LENGTH_SHORT).show();
ListView list = (ListView)findViewById(R.id.contactList);
list.setAdapter(adapter);
}

}

Now we can add new items to the database and the list updates when that is done.

That's all for today.

Thanks for reading!

Reference PAGE TOP

http://kirill-poletaev.blogspot.it/2013/02/android-beginner-tutorial-part-71.html

0 Comments Leave a comment

Please login in order to leave a comment.

Newest first
!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.