Android - Agenda

De Aulas

Links relacionados: Programação para Dispositivos Móveis

Exemplo de Agenda Telefônica no Android

  1. Crie um novo projeto do tipo Empty Activity
  2. Crie uma nova Empty Activity chamada FormActivity;

Strings

Crie as seguintes strings:

 1<resources>
 2    <string name="app_name">AgendaTeste</string>
 3    <string name="strLabelId">ID:</string>
 4    <string name="strLabelNome">Name</string>
 5    <string name="strLabelFone">Fone</string>
 6    <string name="strButtonGravar">Save</string>
 7    <string name="strButtonApagar">Del</string>
 8    <string name="strButtonProcurar">Find</string>
 9    <string name="strButtonLimpar">Clean</string>
10</resources>

Interface

Na interface, insira:

  • 3 textView: ID, Nome e Fone
  • 3 editText: ID, Nome e Fone
  • 4 button: Gravar, Apagar, Procurar, Limpar
  • 1 textView para os Contatos
  1<?xml version="1.0" encoding="utf-8"?>
  2<RelativeLayout
  3    xmlns:android="http://schemas.android.com/apk/res/android"
  4    xmlns:tools="http://schemas.android.com/tools"
  5    android:layout_width="match_parent"
  6    android:layout_height="match_parent"
  7    tools:context="com.project.saulopz.agendateste20171.MainActivity" >
  8
  9    <TextView
 10        android:id="@+id/lableID"
 11        android:layout_width="wrap_content"
 12        android:layout_height="wrap_content"
 13        android:layout_alignParentLeft="true"
 14        android:layout_alignParentTop="true"
 15        android:layout_marginTop="16dp"
 16        android:text="@string/strLabelId" />
 17
 18    <TextView
 19        android:id="@+id/labelNome"
 20        android:layout_width="wrap_content"
 21        android:layout_height="wrap_content"
 22        android:layout_alignLeft="@+id/lableID"
 23        android:layout_below="@+id/lableID"
 24        android:layout_marginTop="19dp"
 25        android:text="@string/strLabelNome" />
 26
 27    <TextView
 28        android:id="@+id/labelFone"
 29        android:layout_width="wrap_content"
 30        android:layout_height="wrap_content"
 31        android:layout_alignLeft="@+id/labelNome"
 32        android:layout_below="@+id/labelNome"
 33        android:layout_marginTop="20dp"
 34        android:text="@string/strLabelFone" />
 35
 36    <EditText
 37        android:id="@+id/editTextID"
 38        android:layout_width="wrap_content"
 39        android:layout_height="wrap_content"
 40        android:layout_alignBaseline="@+id/lableID"
 41        android:layout_alignBottom="@+id/lableID"
 42        android:layout_toRightOf="@+id/labelNome"
 43        android:ems="10"
 44        android:inputType="text" />
 45
 46    <EditText
 47        android:id="@+id/editTextNome"
 48        android:layout_width="wrap_content"
 49        android:layout_height="wrap_content"
 50        android:layout_alignBaseline="@+id/labelNome"
 51        android:layout_alignBottom="@+id/labelNome"
 52        android:layout_alignLeft="@+id/editTextID"
 53        android:ems="10"
 54        android:inputType="text" />
 55
 56    <EditText
 57        android:id="@+id/editTextFone"
 58        android:layout_width="wrap_content"
 59        android:layout_height="wrap_content"
 60        android:layout_alignBaseline="@+id/labelFone"
 61        android:layout_alignBottom="@+id/labelFone"
 62        android:layout_alignLeft="@+id/editTextNome"
 63        android:ems="10"
 64        android:inputType="text" />
 65
 66    <Button
 67        android:id="@+id/buttonGravar"
 68        android:layout_width="wrap_content"
 69        android:layout_height="wrap_content"
 70        android:layout_alignLeft="@+id/labelFone"
 71        android:layout_below="@+id/editTextFone"
 72        android:layout_marginTop="25dp"
 73        android:text="@string/strButtonGravar" />
 74
 75    <Button
 76        android:id="@+id/buttonApagar"
 77        android:layout_width="wrap_content"
 78        android:layout_height="wrap_content"
 79        android:layout_alignBaseline="@+id/buttonGravar"
 80        android:layout_alignBottom="@+id/buttonGravar"
 81        android:layout_toRightOf="@+id/buttonGravar"
 82        android:text="@string/strButtonApagar" />
 83
 84    <Button
 85        android:id="@+id/buttonProcurar"
 86        android:layout_width="wrap_content"
 87        android:layout_height="wrap_content"
 88        android:layout_alignBaseline="@+id/buttonApagar"
 89        android:layout_alignBottom="@+id/buttonApagar"
 90        android:layout_toRightOf="@+id/buttonApagar"
 91        android:text="@string/strButtonProcurar" />
 92
 93    <Button
 94        android:id="@+id/buttonLimpar"
 95        android:layout_width="wrap_content"
 96        android:layout_height="wrap_content"
 97        android:layout_alignParentRight="true"
 98        android:layout_alignTop="@+id/buttonProcurar"
 99        android:text="@string/strButtonLimpar" />
100
101    <TextView
102        android:id="@+id/textViewAgenda"
103        android:layout_width="wrap_content"
104        android:layout_height="wrap_content"
105        android:layout_alignLeft="@+id/buttonGravar"
106        android:layout_centerVertical="true"
107        android:text="TextView" />
108
109</RelativeLayout>

Acesso aos Dados

DatabaseConnection

 1package com.example.agenda;
 2
 3import android.content.Context;
 4import android.database.sqlite.SQLiteDatabase;
 5
 6public class DatabaseConnection {
 7    static private SQLiteDatabase connection = null;
 8    static private String database = "";
 9    static private Context context;
10    static private String table = "create table if not exists agenda ("
11            + "id integer not null primary key autoincrement,"
12            + "nome varchar(100), fone varchar(30))";
13
14    public static void setConfig(String db, Context c) {
15        database = db;
16        context = c;
17    }
18
19    public static SQLiteDatabase getConnection() {
20        if (connection == null) {
21            try {
22                connection = context.openOrCreateDatabase(database, 0, null);
23                connection.execSQL(table);
24            } catch (Exception e) {
25                e.printStackTrace();
26            }
27        }
28        return connection;
29    }
30}

Agenda

 1package com.example.agenda;
 2
 3public class Agenda {
 4    private int id;
 5    private String nome;
 6    private String fone;
 7
 8    public Agenda() {
 9        setId(0);
10        setNome("");
11        setFone("");
12    }
13
14    public Agenda(int id, String nome, String fone) {
15        this.setId(id);
16        this.setNome(nome);
17        this.setFone(fone);
18    }
19
20    public int getId() {
21        return id;
22    }
23
24    public void setId(int id) {
25        this.id = id;
26    }
27
28    public String getNome() {
29        return nome;
30    }
31
32    public void setNome(String nome) {
33        this.nome = nome;
34    }
35
36    public String getFone() {
37        return fone;
38    }
39
40    public void setFone(String fone) {
41        this.fone = fone;
42    }
43
44    public String toString() {
45        return id + ": " + nome + " : " + fone;
46    }
47}

AgendaDAO

 1package com.example.agenda;
 2
 3import java.util.ArrayList;
 4import java.util.List;
 5import android.database.Cursor;
 6import android.database.sqlite.SQLiteDatabase;
 7
 8public class AgendaDAO {
 9    private int posicao;
10    private List<Agenda> agendaList;
11
12    public AgendaDAO() {
13        posicao = 0;
14        agendaList = new ArrayList<Agenda>();
15    }
16
17    public void load() {
18        clear();
19        try {
20            SQLiteDatabase conn = DatabaseConnection.getConnection();
21            Cursor result = conn.query("agenda", null, null, null, null, null,
22                    "nome");
23            while (result.moveToNext()) {
24                int id = result.getInt(result.getColumnIndex("id"));
25                String nome = result.getString(result.getColumnIndex("nome"));
26                String fone = result.getString(result
27                        .getColumnIndex("fone"));
28                agendaList.add(new Agenda(id, nome, fone));
29            }
30        } catch (Exception e) {
31            e.printStackTrace();
32        }
33    }
34
35    public void inserir(Agenda a) {
36        try {
37            SQLiteDatabase conn = DatabaseConnection.getConnection();
38            String query = "insert into agenda (nome, fone) values ('"
39                    + a.getNome() + "', '" + a.getFone() + "')";
40            conn.execSQL(query);
41        } catch (Exception e) {
42            e.printStackTrace();
43        }
44    }
45
46    public void alterar(Agenda a) {
47        try {
48            SQLiteDatabase conn = DatabaseConnection.getConnection();
49            String query = "update agenda set nome='" + a.getNome()
50                    + "', fone='" + a.getFone() + "' where id='" + a.getId()
51                    + "'";
52            conn.execSQL(query);
53        } catch (Exception e) {
54            e.printStackTrace();
55        }
56    }
57
58    public void deletar(Agenda a) {
59        try {
60            SQLiteDatabase conn = DatabaseConnection.getConnection();
61            String query = "delete from agenda where id='" + a.getId() + "'";
62            conn.execSQL(query);
63        } catch (Exception e) {
64            e.printStackTrace();
65        }
66    }
67
68    public Agenda getById(int id) {
69        for (int i = 0; i < agendaList.size(); i++) {
70            Agenda a = agendaList.get(i);
71            if (a.getId() == id) {
72                return a;
73            }
74        }
75        return null;
76    }
77
78    public Agenda next() {
79        Agenda a = null;
80        if (posicao < agendaList.size()) {
81            a = agendaList.get(posicao);
82            posicao++;
83        }
84        return a;
85    }
86
87    public void reset() {
88        posicao = 0;
89    }
90
91    public int size() {
92        return agendaList.size();
93    }
94
95    public void clear() {
96        posicao = 0;
97        agendaList.clear();
98    }
99}

Activity

  1package com.example.agenda;
  2
  3import android.support.v7.app.AppCompatActivity;
  4import android.os.Bundle;
  5import android.app.AlertDialog.Builder;
  6import android.view.View;
  7import android.view.View.OnClickListener;
  8import android.widget.EditText;
  9import android.widget.TextView;
 10
 11public class MainActivity extends AppCompatActivity implements OnClickListener {
 12    private EditText editTextId;
 13    private EditText editTextNome;
 14    private EditText editTextFone;
 15    private TextView textViewAgenda;
 16    private AgendaDAO agenda;
 17
 18    @Override
 19    protected void onCreate(Bundle savedInstanceState) {
 20        super.onCreate(savedInstanceState);
 21        setContentView(R.layout.activity_main);
 22
 23        textViewAgenda = (TextView) findViewById(R.id.textViewAgenda);
 24        editTextId = (EditText) findViewById(R.id.editTextID);
 25        editTextNome = (EditText) findViewById(R.id.editTextNome);
 26        editTextFone = (EditText) findViewById(R.id.editTextFone);
 27
 28        findViewById(R.id.buttonGravar).setOnClickListener(this);
 29        findViewById(R.id.buttonApagar).setOnClickListener(this);
 30        findViewById(R.id.buttonProcurar).setOnClickListener(this);
 31        findViewById(R.id.buttonLimpar).setOnClickListener( this);
 32
 33        DatabaseConnection.setConfig("agendadb", getApplicationContext());
 34        agenda = new AgendaDAO();
 35        loadAgenda();
 36    }
 37
 38    public void dialogo(String titulo, String conteudo) {
 39        Builder builder = new Builder(MainActivity.this);
 40        builder.setTitle(titulo);
 41        builder.setMessage(conteudo);
 42        builder.setNeutralButton("Ok", null);
 43        builder.show();
 44    }
 45
 46    public void limparCampos() {
 47        editTextId.setText("");
 48        editTextNome.setText("");
 49        editTextFone.setText("");
 50    }
 51
 52    public void loadAgenda() {
 53        agenda.load();
 54        Agenda a;
 55        String str = "";
 56        while ((a = agenda.next()) != null) {
 57            str += a.toString() + "\n";
 58        }
 59        textViewAgenda.setText(str);
 60    }
 61
 62    @Override
 63    public void onClick(View v) {
 64        switch (v.getId()) {
 65            case R.id.buttonGravar:
 66                try {
 67                    int id = 0;
 68                    if (editTextId.getText().toString().compareTo("") != 0) {
 69                        id = Integer.valueOf(editTextId.getText().toString());
 70                    }
 71                    Agenda a = agenda.getById(id);
 72                    if (a != null) {
 73                        a.setNome(editTextNome.getText().toString());
 74                        a.setFone(editTextFone.getText().toString());
 75                        agenda.alterar(a);
 76                    } else {
 77                        a = new Agenda(id, editTextNome.getText().toString(),
 78                                editTextFone.getText().toString());
 79                        agenda.inserir(a);
 80                    }
 81                    limparCampos();
 82                    loadAgenda();
 83                } catch (Exception e) {
 84                    dialogo("ERRO", "O ID precisa ser inteiro");
 85                }
 86                break;
 87            case R.id.buttonLimpar:
 88                limparCampos();
 89                break;
 90            case R.id.buttonProcurar:
 91                try {
 92                    int id = Integer.valueOf(editTextId.getText().toString());
 93                    Agenda a = agenda.getById(id);
 94                    if (a != null) {
 95                        editTextNome.setText(a.getNome());
 96                        editTextFone.setText(a.getFone());
 97                    } else {
 98                        dialogo("Not found", "Contato de codigo " + id
 99                                + " nao existe");
100                    }
101                } catch (Exception e) {
102                    dialogo("Erro", "Informe um id inteiro valido");
103                }
104                break;
105            case R.id.buttonApagar:
106                try {
107                    int id = Integer.valueOf(editTextId.getText().toString());
108                    Agenda a = agenda.getById(id);
109                    if (a != null) {
110                        agenda.deletar(a);
111                    } else {
112                        dialogo("Not found", "Contato de codigo " + id
113                                + " nao existe");
114                    }
115                } catch (Exception e) {
116                    dialogo("Erro", "Informe um id inteiro valido");
117                }
118                limparCampos();
119                loadAgenda();
120                break;
121        }
122    }
123}