package br.com.caelum.testebancodados;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by matheus on 25/08/16.
*/
public class AlunoDao extends SQLiteOpenHelper {
public AlunoDao(Context context) {
super(context, "Teste", null, 1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("Create table Alunos(id integer primary key, nome text not null);");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void salva(Aluno aluno) {
Log.d("Teste", "nome :" + aluno.getNome());
ContentValues valores = new ContentValues();
valores.put("nome", aluno.getNome());
long insert = getWritableDatabase().insert("Alunos", null, valores);
Log.d("id", "id" + insert);
}
public List<Aluno> listagem() {
List<Aluno> lista = new ArrayList<>();
Cursor cursor = getReadableDatabase().rawQuery("select * from Alunos", null);
while (cursor.moveToNext()) {
Aluno aluno = new Aluno();
aluno.setId(cursor.getLong(cursor.getColumnIndex("id")));
aluno.setNome(cursor.getString(cursor.getColumnIndex("nome")));
lista.add(aluno);
}
return lista;
}
public boolean isAlunoInTheDB(int id) {
boolean result = false;
SQLiteDatabase db = getReadableDatabase();
String query = "SELECT * FROM alunos WHERE id=" + id + ";";
Cursor c = db.rawQuery(query, null);
if (c.getCount() > 0) {
result = true;
}
return result;
}
}