· 8 years ago · Jun 24, 2018, 04:52 PM
1private static final String DATABASE_NAME = "bancodedados.db";
2private static final int DATABASE_VERSION = 1;
3private static final String TABLE_NAME = "cadastro";
4
5private Context context;
6private SQLiteDatabase db;
7
8private SQLiteStatement InsertStnt;
9private static final String Insert = "insert into " + TABLE_NAME + " (nome, cpf, idade, telefone, email) values (?, ?, ?, ?, ?)";
10
11
12public DBcadastro(Context context){
13 this.context = context;
14 Opencadastro opencadastro = new Opencadastro(this.context);
15 this.db = opencadastro.getWritableDatabase();
16 this.InsertStnt = this.db.compileStatement(Insert);
17}
18
19public long insert (String nome, int cpf,int idade, int telefone, String email ){
20 this.InsertStnt.bindString(1,nome);
21 this.InsertStnt.bindLong(2,cpf);
22 this.InsertStnt.bindLong(3,idade);
23 this.InsertStnt.bindLong(4,telefone);
24 this.InsertStnt.bindString(5,email);
25 return this.InsertStnt.executeInsert();
26}
27
28public void deleteAll (){
29 this.db.delete(TABLE_NAME,null, null);
30}
31
32public List<cadastro> queryGetALL(){
33 List<cadastro> list = new ArrayList<cadastro>();
34
35 try {
36
37 Cursor cursor = this.db.query (TABLE_NAME, new String[] {"nome", "cpf","idade", "telefone", "email"},
38 null, null, null, null, null);
39
40 int registros = cursor.getCount();
41
42 if (registros != 0){
43 cursor.moveToFirst();
44
45 do {
46 cadastro cadastro = new cadastro(cursor.getString(0), cursor.getInt(1), cursor.getInt(2),cursor.getInt(3),cursor.getString(4));
47 list.add(cadastro);
48 } while (cursor.moveToNext());
49
50 if (cursor != null && ! cursor.isClosed())
51 cursor.close();
52 return list;
53 }else
54 return null;
55
56 }
57
58 catch (Exception err) {
59 return null;
60 }
61}
62
63private static class Opencadastro extends SQLiteOpenHelper{
64 Opencadastro(Context context){
65 super(context, TABLE_NAME, null, DATABASE_VERSION);
66
67 }
68
69 public void onCreate (SQLiteDatabase db){
70 String sql = "CREATE TABLE IP NOT EXISTS " + TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT, nome TEXT " +
71 "cpf INT, idade INT, telefone INT, email TEXT);";
72 db.execSQL(sql);
73 }
74
75 public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion){
76 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
77 onCreate(db);
78 }
79}