Android - Lista de Contatos

De Aulas

Conteúdos relacionados: Dispositivos Móveis

  • Criar uma Empty Activity;

string.xml

 1<resources>
 2    <string name="app_name">Contacts</string>
 3    <string name="field_name">Name</string>
 4    <string name="field_email">E-mail</string>
 5    <string name="field_phone">Phone</string>
 6    <string name="button_ok">OK</string>
 7    <string name="button_clear">Clear</string>
 8    <string name="error_noname">Please, enter with a name.</string>
 9    <string name="error_title">Attention!</string>
10    <string name="alert_erase">You really want erase contact</string>
11</resources>

activity_main.xml

 1<?xml version="1.0" encoding="utf-8"?>
 2<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3    xmlns:app="http://schemas.android.com/apk/res-auto"
 4    xmlns:tools="http://schemas.android.com/tools"
 5    android:layout_width="match_parent"
 6    android:layout_height="match_parent"
 7    tools:context=".MainActivity">
 8
 9    <EditText
10        android:id="@+id/editTextName"
11        android:layout_width="0dp"
12        android:layout_height="wrap_content"
13        android:layout_marginLeft="8dp"
14        android:layout_marginRight="8dp"
15        android:layout_marginTop="8dp"
16        android:ems="10"
17        android:hint="@string/field_name"
18        android:inputType="textPersonName"
19        app:layout_constraintLeft_toLeftOf="parent"
20        app:layout_constraintRight_toRightOf="parent"
21        app:layout_constraintTop_toTopOf="parent"
22        android:layout_marginStart="8dp"
23        android:layout_marginEnd="8dp"/>
24
25    <EditText
26        android:id="@+id/editTextPhone"
27        android:layout_width="0dp"
28        android:layout_height="wrap_content"
29        android:layout_marginLeft="8dp"
30        android:layout_marginRight="8dp"
31        android:layout_marginTop="8dp"
32        android:ems="10"
33        android:hint="@string/field_phone"
34        android:inputType="phone"
35        app:layout_constraintLeft_toLeftOf="parent"
36        app:layout_constraintRight_toRightOf="parent"
37        app:layout_constraintTop_toBottomOf="@+id/editTextName" />
38
39    <EditText
40        android:id="@+id/editTextEmail"
41        android:layout_width="0dp"
42        android:layout_height="wrap_content"
43        android:layout_marginLeft="8dp"
44        android:layout_marginRight="8dp"
45        android:layout_marginTop="8dp"
46        android:ems="10"
47        android:hint="@string/field_email"
48        android:inputType="textEmailAddress"
49        app:layout_constraintLeft_toLeftOf="parent"
50        app:layout_constraintRight_toRightOf="parent"
51        app:layout_constraintTop_toBottomOf="@+id/editTextPhone" />
52
53    <Button
54        android:id="@+id/buttonOk"
55        android:layout_width="wrap_content"
56        android:layout_height="wrap_content"
57        android:layout_marginLeft="8dp"
58        android:layout_marginTop="8dp"
59        android:text="@string/button_ok"
60        app:layout_constraintLeft_toLeftOf="parent"
61        app:layout_constraintTop_toBottomOf="@+id/editTextEmail"
62        android:layout_marginStart="8dp"
63        tools:ignore="RtlHardcoded" />
64
65    <Button
66        android:id="@+id/buttonClear"
67        android:layout_width="wrap_content"
68        android:layout_height="wrap_content"
69        android:layout_marginEnd="8dp"
70        android:layout_marginRight="8dp"
71        android:layout_marginTop="8dp"
72        android:text="@string/button_clear"
73        app:layout_constraintRight_toRightOf="parent"
74        app:layout_constraintTop_toBottomOf="@+id/editTextEmail"
75        tools:ignore="RtlHardcoded" />
76
77    <ListView
78        android:id="@+id/listContacts"
79        android:layout_width="0dp"
80        android:layout_height="0dp"
81        android:layout_marginBottom="8dp"
82        android:layout_marginEnd="8dp"
83        android:layout_marginLeft="8dp"
84        android:layout_marginRight="8dp"
85        android:layout_marginStart="8dp"
86        android:layout_marginTop="8dp"
87        app:layout_constraintBottom_toBottomOf="parent"
88        app:layout_constraintHorizontal_bias="0.0"
89        app:layout_constraintLeft_toLeftOf="parent"
90        app:layout_constraintRight_toRightOf="parent"
91        app:layout_constraintTop_toBottomOf="@+id/buttonOk"
92        app:layout_constraintVertical_bias="0.0"/>
93
94</android.support.constraint.ConstraintLayout>

Contact.java

 1package com.saulopz.agenda;
 2
 3import android.provider.BaseColumns;
 4
 5class Contact implements BaseColumns {
 6	static final String TABLE_NAME = "contact";
 7	static final String COLUMN_NAME_NAME = "name";
 8	static final String COLUMN_NAME_EMAIL = "email";
 9	static final String COLUMN_NAME_PHONE = "phone";
10
11	private String name;
12	private String email;
13	private String phone;
14
15	Contact(String name, String email, String phone) {
16		setName(name);
17		setEmail(email);
18		setPhone(phone);
19	}
20
21	public String getName() {
22		return name;
23	}
24
25	public void setName(String name) {
26		this.name = name;
27	}
28
29	public String getEmail() {
30		return email;
31	}
32
33	public void setEmail(String email) {
34		this.email = email;
35	}
36
37	public String getPhone() {
38		return phone;
39	}
40
41	public void setPhone(String phone) {
42		this.phone = phone;
43	}
44}

DBHelper.java

 1package com.saulopz.agenda;
 2
 3import android.content.Context;
 4import android.database.sqlite.SQLiteDatabase;
 5import android.database.sqlite.SQLiteOpenHelper;
 6
 7public class DBHelper extends SQLiteOpenHelper {
 8    private static final int DATABASE_VERSION = 1;
 9    private static final String DATABASE_NAME = "contacts.db";
10
11    DBHelper(Context context) {
12        super(context, DATABASE_NAME, null, DATABASE_VERSION);
13    }
14
15    @Override
16    public void onCreate(SQLiteDatabase db) {
17        String sql = "CREATE TABLE IF NOT EXISTS " + Contact.TABLE_NAME + " (" +
18                Contact.COLUMN_NAME_NAME + " VARCHAR(255) NOT NULL PRIMARY KEY, " +
19                Contact.COLUMN_NAME_EMAIL + " VARCHAR(255) NOT NULL, " +
20                Contact.COLUMN_NAME_PHONE + " VARCHAR(255) NOT NULL)";
21        db.execSQL(sql);
22    }
23
24    @Override
25    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
26        String sql = "DROP TABLE IF EXISTS " + Contact.TABLE_NAME;
27        db.execSQL(sql);
28    }
29}

ContactDAO.java

 1package com.saulopz.agenda;
 2
 3import android.content.ContentValues;
 4import android.content.Context;
 5import android.database.Cursor;
 6import android.database.sqlite.SQLiteDatabase;
 7
 8import java.util.ArrayList;
 9import java.util.List;
10
11public class ContactDAO {
12    private DBHelper dbHelper;
13    private List<Contact> contacts;
14    public List<String> names;
15
16    ContactDAO(Context context) {
17        dbHelper = new DBHelper(context);
18        contacts = new ArrayList<>();
19        names = new ArrayList<>();
20        load();
21    }
22
23    private void load() {
24        names.clear();
25        contacts.clear();
26        SQLiteDatabase db = dbHelper.getReadableDatabase();
27        Cursor cursor = db.query(Contact.TABLE_NAME, null, null, null, null, null, null);
28        while (cursor.moveToNext()) {
29            String name = cursor.getString(cursor.getColumnIndex(Contact.COLUMN_NAME_NAME));
30            String email = cursor.getString(cursor.getColumnIndex(Contact.COLUMN_NAME_EMAIL));
31            String phone = cursor.getString(cursor.getColumnIndex(Contact.COLUMN_NAME_PHONE));
32            contacts.add(new Contact(name, email, phone));
33            names.add(name);
34        }
35        cursor.close();
36    }
37
38    public void insert(Contact contact) {
39        SQLiteDatabase db = dbHelper.getWritableDatabase();
40        ContentValues values = new ContentValues();
41        values.put(Contact.COLUMN_NAME_NAME, contact.getName());
42        values.put(Contact.COLUMN_NAME_EMAIL, contact.getEmail());
43        values.put(Contact.COLUMN_NAME_PHONE, contact.getPhone());
44        db.insert(Contact.TABLE_NAME, null, values);
45        contacts.add(contact);
46        names.add(contact.getName());
47    }
48
49    public void update(Contact contact) {
50        SQLiteDatabase db = dbHelper.getReadableDatabase();
51        ContentValues values = new ContentValues();
52
53        values.put(Contact.COLUMN_NAME_NAME, contact.getName());
54        values.put(Contact.COLUMN_NAME_EMAIL, contact.getEmail());
55        values.put(Contact.COLUMN_NAME_PHONE, contact.getPhone());
56
57        String selection = Contact.COLUMN_NAME_NAME + " = ? ";
58        String[] selectionArgs = {contact.getName()};
59
60        db.update(Contact.TABLE_NAME, values, selection, selectionArgs);
61
62        Contact c = getByName(contact.getName());
63        c.setName(contact.getName());
64        c.setEmail(contact.getEmail());
65        c.setPhone(contact.getPhone());
66    }
67
68    public void delete(Contact contact) {
69        SQLiteDatabase db = dbHelper.getWritableDatabase();
70        String selection = Contact.COLUMN_NAME_NAME + " = ?";
71        String[] selectionArgs = {contact.getName()};
72        db.delete(Contact.TABLE_NAME, selection, selectionArgs);
73        contacts.remove(contact);
74        names.remove(contact.getName());
75    }
76
77    public Boolean contactExist(String name) {
78        return getByName(name) != null;
79    }
80
81    public Contact getByName(String name) {
82        for (Contact contact : contacts) {
83            if (contact.getName().equals(name)) {
84                return contact;
85            }
86        }
87        return null;
88    }
89
90    public int size() {
91        return contacts.size();
92    }
93}

MainActivity.java

  1package com.saulopz.agenda;
  2
  3import android.app.AlertDialog.Builder;
  4import android.content.DialogInterface;
  5import android.os.Bundle;
  6import android.support.v7.app.AppCompatActivity;
  7import android.view.View;
  8import android.view.View.OnClickListener;
  9import android.widget.AdapterView;
 10import android.widget.ArrayAdapter;
 11import android.widget.EditText;
 12import android.widget.ListView;
 13
 14public class MainActivity extends AppCompatActivity implements OnClickListener {
 15    private EditText editTextName;
 16    private EditText editTextEmail;
 17    private EditText editTextPhone;
 18    private ArrayAdapter<String> adapter;
 19    private ContactDAO contactDAO;
 20
 21    @Override
 22    protected void onCreate(Bundle savedInstanceState) {
 23        super.onCreate(savedInstanceState);
 24        setContentView(R.layout.activity_main);
 25
 26        contactDAO = new ContactDAO(this);
 27
 28        editTextName = findViewById(R.id.editTextName);
 29        editTextEmail = findViewById(R.id.editTextEmail);
 30        editTextPhone = findViewById(R.id.editTextPhone);
 31        findViewById(R.id.buttonOk).setOnClickListener(this);
 32        findViewById(R.id.buttonClear).setOnClickListener(this);
 33
 34        ListView listContacts = findViewById(R.id.listContacts);
 35        adapter = new ArrayAdapter<>(this,
 36                android.R.layout.simple_list_item_1,
 37                android.R.id.text1,
 38                contactDAO.names);
 39        listContacts.setAdapter(adapter);
 40        adapter.notifyDataSetChanged();
 41        listContacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
 42            public void onItemClick(AdapterView<?> parent, View view,
 43                                    int position, long id) {
 44                String name = (String) parent.getItemAtPosition(position);
 45                Contact contact = (contactDAO.getByName(name));
 46                editTextName.setText(contact.getName());
 47                editTextEmail.setText(contact.getEmail());
 48                editTextPhone.setText(contact.getPhone());
 49            }
 50        });
 51        listContacts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
 52            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
 53                                           int pos, long id) {
 54                String name = (String) arg0.getItemAtPosition(pos);
 55                Contact contact = (contactDAO.getByName(name));
 56                dialogErase(getResources().getString(R.string.error_title),
 57                        getResources().getString(R.string.error_noname) + " " + name + "?", contact);
 58                return true;
 59            }
 60        });
 61    }
 62
 63    @Override
 64    public void onClick(View v) {
 65        switch (v.getId()) {
 66            case R.id.buttonOk:
 67                if (editTextName.getText().toString().trim().equals("")) {
 68                    dialog(getResources().getString(R.string.error_title),
 69                            getResources().getString(R.string.error_noname));
 70                } else {
 71                    Contact contact = new Contact(
 72                            editTextName.getText().toString(),
 73                            editTextEmail.getText().toString(),
 74                            editTextPhone.getText().toString());
 75                    if (contactDAO.contactExist(contact.getName())) {
 76                        contactDAO.update(contact);
 77                    } else {
 78                        contactDAO.insert(contact);
 79                    }
 80                    adapter.notifyDataSetChanged();
 81                }
 82                break;
 83            case R.id.buttonClear:
 84                editTextName.setText("");
 85                editTextEmail.setText("");
 86                editTextPhone.setText("");
 87                break;
 88        }
 89    }
 90
 91    public void dialog(String title, String content) {
 92        Builder builder = new Builder(MainActivity.this);
 93        builder.setTitle(title);
 94        builder.setMessage(content);
 95        builder.setNeutralButton("Ok", null);
 96        builder.show();
 97    }
 98
 99    public void dialogErase(String title, String content, final Contact contact) {
100        Builder builder = new Builder(MainActivity.this);
101        builder.setTitle(title);
102        builder.setMessage(content);
103        builder.setCancelable(false);
104        builder.setPositiveButton("ok",
105                new DialogInterface.OnClickListener() {
106                    public void onClick(DialogInterface dialog, int id) {
107                        contactDAO.delete(contact);
108                        adapter.notifyDataSetChanged();
109                    }
110                });
111        builder.setNegativeButton("cancel",
112                new DialogInterface.OnClickListener() {
113                    public void onClick(DialogInterface dialog, int id) {
114                        // do nothing
115                    }
116                });
117        builder.show();
118    }
119}