· 8 years ago · Dec 16, 2017, 08:50 PM
1package com.example.caiomedeiros.projetofinal;
2
3
4import android.content.Context;
5import android.database.Cursor;
6import android.database.sqlite.SQLiteDatabase;
7import android.database.sqlite.SQLiteOpenHelper;
8import android.database.sqlite.SQLiteStatement;
9
10import java.util.ArrayList;
11import java.util.List;
12
13public class DBHelper {
14 private static final String DATABASE_NAME = "bancodedados.db";
15 private static final int DATABASE_VERSION = 1;
16 private static final String TABLE_NAME = "tabela";
17
18 private Context context;
19 private SQLiteDatabase db;
20
21 private SQLiteStatement insertStnt;
22 private static final String INSERT = "insert into " + TABLE_NAME + " (nome, cpf, idade, telefone, email) values (?,?,?,?,?)";
23
24 public DBHelper(Context context) {
25 this.context = context;
26 OpenHelper openHelper = new OpenHelper(this.context);
27 this.db = openHelper.getWritableDatabase();
28 this.insertStnt = this.db.compileStatement(INSERT);
29 }
30
31 public long insert(String nome, String cpf, String idade, String telefone, String email) {
32 this.insertStnt.bindString(0, nome);
33 this.insertStnt.bindString(1, cpf);
34 this.insertStnt.bindString(2, idade);
35 this.insertStnt.bindString(3, telefone);
36 this.insertStnt.bindString(4, email);
37
38 return this.insertStnt.executeInsert();
39 }
40
41 public void deleteAll() {
42 this.db.delete(TABLE_NAME, null, null);
43 }
44
45 public List<PessoaFisica> queryGetAll() {
46 List<PessoaFisica> list = new ArrayList<PessoaFisica>();
47
48 try {
49 Cursor cursor = this.db.query(TABLE_NAME, new String[]{"nome", "cpf", "idade", "telefone", "email"},
50 null, null, null, null, null, null);
51 int nregistros = cursor.getCount();
52 if (nregistros != 0) {
53 cursor.moveToFirst();
54 do {
55 PessoaFisica pessoa = new PessoaFisica(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
56 list.add(pessoa);
57 } while (cursor.moveToNext());
58
59 if (cursor != null && !cursor.isClosed()) {
60 cursor.close();
61 }
62 return list;
63 }
64 else {
65 return null;
66 }
67 }catch(Exception err){
68 return null;
69 }
70 }
71
72 private static class OpenHelper extends SQLiteOpenHelper{
73 OpenHelper(Context context){
74 super(context,DATABASE_NAME,null,DATABASE_VERSION);
75 }
76 public void onCreate(SQLiteDatabase db){
77 String sql= "CREATE TABLE IF NOT EXISTS "+ TABLE_NAME+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, nome text,cpf text, idade text, telefone text, email text);";
78 db.execSQL(sql);
79 }
80 public void onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion){
81 db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
82 }
83
84 }
85
86}