andoid
21/05/2012
0
so pra dizer se esta ok ou se tem alguma coisa errada. o dao e o repositorio
public class RepositorioFeira { private static final String[] CAMPOS_FEIRA = { id, mercado, data }; private static final String[] CAMPOS_ITEM = { id_feira, produto, qtde, preco }; private SQLiteDatabase db; private static RepositorioFeira instance = new RepositorioFeira(); public static RepositorioFeira getInstance(Context ctx) { if (instance.db == null || !instance.db.isOpen()) { instance.db = new DBHelper(ctx).getWritableDatabase(); } return instance; } private RepositorioFeira() { } public long salvar(Feira feira) { int id = feira.getId(); if (id == 0) { return inserir(feira); } else { return atualizar(feira); } } private long inserir(Feira f) { long id_feira = -1; db.beginTransaction(); try { ContentValues cv = new ContentValues(); cv.put(CAMPOS_FEIRA[1], f.getMercado()); cv.put(CAMPOS_FEIRA[2], Util.getString(f.getData(), Util.FORMATO_DATA_BD)); id_feira = db.insert(DBHelper.TBL_FEIRA, null, cv); if (id_feira != -1) { boolean deuErro = false; for (Item item : f.getItens()) { ContentValues icv = new ContentValues(); icv.put(CAMPOS_ITEM[0], id_feira); icv.put(CAMPOS_ITEM[1], item.getProduto()); icv.put(CAMPOS_ITEM[2], item.getQtde()); icv.put(CAMPOS_ITEM[3], item.getPreco()); if (db.insert(DBHelper.TBL_ITEM, null, icv) == -1) { deuErro = true; break; } } if (!deuErro) { db.setTransactionSuccessful(); } } } finally { db.endTransaction(); } return id_feira; } private long atualizar(Feira f) { boolean deuErro = false; db.beginTransaction(); try { ContentValues cv = new ContentValues(); cv.put(CAMPOS_FEIRA[1], f.getMercado()); cv.put(CAMPOS_FEIRA[2], Util.getString(f.getData(), Util.FORMATO_DATA_BD)); deuErro = db.update(DBHelper.TBL_FEIRA, cv, CAMPOS_FEIRA[0] + = ?, new String[] { String.valueOf(f.getId()) }) == 0; if (!deuErro) { db.delete(DBHelper.TBL_ITEM, CAMPOS_ITEM[0] + = + f.getId(), null); for (Item item : f.getItens()) { ContentValues icv = new ContentValues(); icv.put(CAMPOS_ITEM[0], f.getId()); icv.put(CAMPOS_ITEM[1], item.getProduto()); icv.put(CAMPOS_ITEM[2], item.getQtde()); icv.put(CAMPOS_ITEM[3], item.getPreco()); if (db.insert(DBHelper.TBL_ITEM, null, icv) == -1) { deuErro = true; break; } } if (!deuErro) { db.setTransactionSuccessful(); } } } finally { db.endTransaction(); } return f.getId(); } public void excluir(int id) { db.beginTransaction(); try { db.delete(DBHelper.TBL_ITEM, CAMPOS_ITEM[0] + =?, new String[] { String.valueOf(id) }); db.delete(DBHelper.TBL_FEIRA, CAMPOS_FEIRA[0] + =?, new String[] { String.valueOf(id) }); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public Feira getFeira(int id) { Cursor c = db.query(DBHelper.TBL_FEIRA, null, CAMPOS_FEIRA[0] + = + id, null, null, null, null); if (c.getCount() > 0) { c.moveToFirst(); return fillFeira(c); } return null; } private Feira fillFeira(Cursor c) { int id = c.getInt(c.getColumnIndex(CAMPOS_FEIRA[0])); String mercado = c.getString(c.getColumnIndex(CAMPOS_FEIRA[1])); Date data = Util.getDate( c.getString(c.getColumnIndex(CAMPOS_FEIRA[2])), Util.FORMATO_DATA_BD); Feira feira = new Feira(id, mercado, data); Cursor ic = db.query(DBHelper.TBL_ITEM, null, id_feira = ?, new String[] { String.valueOf(id) }, null, null, null); ic.moveToFirst(); while (!ic.isAfterLast()) { feira.getItens().add(fillItem(ic)); ic.moveToNext(); } return feira; } private Item fillItem(Cursor c) { String produto = c.getString(c.getColumnIndex(CAMPOS_ITEM[1])); double qtde = c.getDouble(c.getColumnIndex(CAMPOS_ITEM[2])); double preco = c.getDouble(c.getColumnIndex(CAMPOS_ITEM[3])); return new Item(produto, qtde, preco); } public List<Feira> listaFeiras() { List<Feira> lista = new ArrayList<Feira>(); Cursor c = db.query(DBHelper.TBL_FEIRA, null, null, null, null, null, null); c.moveToFirst(); while (!c.isAfterLast()) { Feira feira = fillFeira(c); lista.add(feira); c.moveToNext(); } return lista; } } /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Dao; import Classes.Cliente; import Conexao.SqliteHelper; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; /** * * @author Peter */ public class RepositorioCliente { private SQLiteDatabase database; private SqliteHelper dbHelper; private String[] Colunas = {_idCliente, nome,endereco, bairro, cidade, uf, d_nascimento, cep, cpf, email, login, senha}; public RepositorioCliente(Context context) { dbHelper = new SqliteHelper(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public Cliente incluirCliente(Cliente cliente) { ContentValues valores = new ContentValues(); valores.put(nome, cliente.getNome()); valores.put(endereco, cliente.getEndereco()); valores.put(bairro, cliente.getBairro()); valores.put(cidade, cliente.getCidade()); valores.put(uf, cliente.getUf()); valores.put(d_nascimento, cliente.getData_nasc()); valores.put(cep, cliente.getCep()); valores.put(cpf, cliente.getCpf()); valores.put(email, cliente.getEmail()); valores.put(login, cliente.getLogin()); valores.put(senha, cliente.getSenha()); //getWritableDatabase().insert(Tabela, null, valores); long insertId = database.insert(SqliteHelper.Tabela_Cliente, null, valores); Cursor cursor = database.query(SqliteHelper.Tabela_Cliente, Colunas, _idCliente + = + insertId, null, null, null, null); cursor.moveToFirst(); Cliente newCliente = cursorToCliente(cursor); cursor.close(); return newCliente; } public void deleteCliente(Cliente cliente) { long id = cliente.getIdCliente(); System.out.println(Cliente deleted with id: + id); database.delete(SqliteHelper.Tabela_Cliente, _idCliente + = + id, null); } /* public List<Comment> getAllComments() { List<Comment> comments = new ArrayList<Comment>(); Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS, allColumns, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Comment comment = cursorToComment(cursor); comments.add(comment); cursor.moveToNext(); } // Make sure to close the cursor cursor.close(); return comments; } * * */ private Cliente cursorToCliente(Cursor c) { Cliente cliente = new Cliente(); cliente.setIdCliente(c.getInt(0)); cliente.setNome(c.getString(1)); cliente.setEndereco(c.getString(2)); cliente.setBairro(c.getString(3)); cliente.setCidade(c.getString(4)); cliente.setUf(c.getString(5)); cliente.setData_nasc(c.getString(6)); cliente.setCep(c.getString(7)); cliente.setCpf(c.getInt(8)); cliente.setEmail(c.getString(9)); cliente.setLogin(c.getString(10)); cliente.setSenha(c.getString(11)); return cliente; } }
Lu
Posts
21/05/2012
Lu
so pra dizer se esta ok ou se tem alguma coisa errada. o dao e o repositorio
esse repositorio e o q eu stava vendo, bem dferente da forma q stou tentando fazer
public class RepositorioFeira { private static final String[] CAMPOS_FEIRA = { id, mercado, data }; private static final String[] CAMPOS_ITEM = { id_feira, produto, qtde, preco }; private SQLiteDatabase db; private static RepositorioFeira instance = new RepositorioFeira(); public static RepositorioFeira getInstance(Context ctx) { if (instance.db == null || !instance.db.isOpen()) { instance.db = new DBHelper(ctx).getWritableDatabase(); } return instance; } private RepositorioFeira() { } public long salvar(Feira feira) { int id = feira.getId(); if (id == 0) { return inserir(feira); } else { return atualizar(feira); } } private long inserir(Feira f) { long id_feira = -1; db.beginTransaction(); try { ContentValues cv = new ContentValues(); cv.put(CAMPOS_FEIRA[1], f.getMercado()); cv.put(CAMPOS_FEIRA[2], Util.getString(f.getData(), Util.FORMATO_DATA_BD)); id_feira = db.insert(DBHelper.TBL_FEIRA, null, cv); if (id_feira != -1) { boolean deuErro = false; for (Item item : f.getItens()) { ContentValues icv = new ContentValues(); icv.put(CAMPOS_ITEM[0], id_feira); icv.put(CAMPOS_ITEM[1], item.getProduto()); icv.put(CAMPOS_ITEM[2], item.getQtde()); icv.put(CAMPOS_ITEM[3], item.getPreco()); if (db.insert(DBHelper.TBL_ITEM, null, icv) == -1) { deuErro = true; break; } } if (!deuErro) { db.setTransactionSuccessful(); } } } finally { db.endTransaction(); } return id_feira; } private long atualizar(Feira f) { boolean deuErro = false; db.beginTransaction(); try { ContentValues cv = new ContentValues(); cv.put(CAMPOS_FEIRA[1], f.getMercado()); cv.put(CAMPOS_FEIRA[2], Util.getString(f.getData(), Util.FORMATO_DATA_BD)); deuErro = db.update(DBHelper.TBL_FEIRA, cv, CAMPOS_FEIRA[0] + = ?, new String[] { String.valueOf(f.getId()) }) == 0; if (!deuErro) { db.delete(DBHelper.TBL_ITEM, CAMPOS_ITEM[0] + = + f.getId(), null); for (Item item : f.getItens()) { ContentValues icv = new ContentValues(); icv.put(CAMPOS_ITEM[0], f.getId()); icv.put(CAMPOS_ITEM[1], item.getProduto()); icv.put(CAMPOS_ITEM[2], item.getQtde()); icv.put(CAMPOS_ITEM[3], item.getPreco()); if (db.insert(DBHelper.TBL_ITEM, null, icv) == -1) { deuErro = true; break; } } if (!deuErro) { db.setTransactionSuccessful(); } } } finally { db.endTransaction(); } return f.getId(); } public void excluir(int id) { db.beginTransaction(); try { db.delete(DBHelper.TBL_ITEM, CAMPOS_ITEM[0] + =?, new String[] { String.valueOf(id) }); db.delete(DBHelper.TBL_FEIRA, CAMPOS_FEIRA[0] + =?, new String[] { String.valueOf(id) }); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public Feira getFeira(int id) { Cursor c = db.query(DBHelper.TBL_FEIRA, null, CAMPOS_FEIRA[0] + = + id, null, null, null, null); if (c.getCount() > 0) { c.moveToFirst(); return fillFeira(c); } return null; } private Feira fillFeira(Cursor c) { int id = c.getInt(c.getColumnIndex(CAMPOS_FEIRA[0])); String mercado = c.getString(c.getColumnIndex(CAMPOS_FEIRA[1])); Date data = Util.getDate( c.getString(c.getColumnIndex(CAMPOS_FEIRA[2])), Util.FORMATO_DATA_BD); Feira feira = new Feira(id, mercado, data); Cursor ic = db.query(DBHelper.TBL_ITEM, null, id_feira = ?, new String[] { String.valueOf(id) }, null, null, null); ic.moveToFirst(); while (!ic.isAfterLast()) { feira.getItens().add(fillItem(ic)); ic.moveToNext(); } return feira; } private Item fillItem(Cursor c) { String produto = c.getString(c.getColumnIndex(CAMPOS_ITEM[1])); double qtde = c.getDouble(c.getColumnIndex(CAMPOS_ITEM[2])); double preco = c.getDouble(c.getColumnIndex(CAMPOS_ITEM[3])); return new Item(produto, qtde, preco); } public List<Feira> listaFeiras() { List<Feira> lista = new ArrayList<Feira>(); Cursor c = db.query(DBHelper.TBL_FEIRA, null, null, null, null, null, null); c.moveToFirst(); while (!c.isAfterLast()) { Feira feira = fillFeira(c); lista.add(feira); c.moveToNext(); } return lista; } } e esse e o meu
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Dao; import Classes.Cliente; import Conexao.SqliteHelper; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; /** * * @author Peter */ public class RepositorioCliente { private SQLiteDatabase database; private SqliteHelper dbHelper; private String[] Colunas = {_idCliente, nome,endereco, bairro, cidade, uf, d_nascimento, cep, cpf, email, login, senha}; public RepositorioCliente(Context context) { dbHelper = new SqliteHelper(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public Cliente incluirCliente(Cliente cliente) { ContentValues valores = new ContentValues(); valores.put(nome, cliente.getNome()); valores.put(endereco, cliente.getEndereco()); valores.put(bairro, cliente.getBairro()); valores.put(cidade, cliente.getCidade()); valores.put(uf, cliente.getUf()); valores.put(d_nascimento, cliente.getData_nasc()); valores.put(cep, cliente.getCep()); valores.put(cpf, cliente.getCpf()); valores.put(email, cliente.getEmail()); valores.put(login, cliente.getLogin()); valores.put(senha, cliente.getSenha()); //getWritableDatabase().insert(Tabela, null, valores); long insertId = database.insert(SqliteHelper.Tabela_Cliente, null, valores); Cursor cursor = database.query(SqliteHelper.Tabela_Cliente, Colunas, _idCliente + = + insertId, null, null, null, null); cursor.moveToFirst(); Cliente newCliente = cursorToCliente(cursor); cursor.close(); return newCliente; } public void deleteCliente(Cliente cliente) { long id = cliente.getIdCliente(); System.out.println(Cliente deleted with id: + id); database.delete(SqliteHelper.Tabela_Cliente, _idCliente + = + id, null); } /* public List<Comment> getAllComments() { List<Comment> comments = new ArrayList<Comment>(); Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS, allColumns, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Comment comment = cursorToComment(cursor); comments.add(comment); cursor.moveToNext(); } // Make sure to close the cursor cursor.close(); return comments; } * * */ private Cliente cursorToCliente(Cursor c) { Cliente cliente = new Cliente(); cliente.setIdCliente(c.getInt(0)); cliente.setNome(c.getString(1)); cliente.setEndereco(c.getString(2)); cliente.setBairro(c.getString(3)); cliente.setCidade(c.getString(4)); cliente.setUf(c.getString(5)); cliente.setData_nasc(c.getString(6)); cliente.setCep(c.getString(7)); cliente.setCpf(c.getInt(8)); cliente.setEmail(c.getString(9)); cliente.setLogin(c.getString(10)); cliente.setSenha(c.getString(11)); return cliente; } }
21/05/2012
Lu
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Dao; import Classes.Cliente; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; public class ClienteDao extends SQLiteOpenHelper { private static final String Tabela = Cliente; private static final int Version = 1; private String[] Colunas = {_idCliente, nome,endereco, bairro, cidade, uf, d_nascimento, cep, cpf, email, login, senha}; public ClienteDao(Context context){ super(context ,Tabela, null, Version); } @Override public void onCreate(SQLiteDatabase jq_bd) { String sql = CREATE TABLE + Tabela + (_idCliente INTEGER PRIMARY KEY AUTOINCREMENT, + nome TEXT NOT NULL, + endereco TEXT NOT NULL,+ bairro TEXT NOT NULL + cidade TEXT NOT NULL,+ uf TEXT NOT NULL, + d_nascimento TEXT NOT NULL,+ cep TEXT NOT NULL, + cpf TEXT NOT NULL, + email TEXT NOT NULL, + login TEXT NOT NULL, + senha TEXT NOT NULL + );; jq_bd.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase jq_bd, int oldVersion, int newVersion) { jq_bd.execSQL(DROP TABLE IF EXISTS + ClienteDao.Tabela); this.onCreate(jq_bd); } public void inserirCliente(Cliente cliente){ ContentValues valores = new ContentValues(); valores.put(nome, cliente.getNome()); valores.put(endereco, cliente.getEndereco()); valores.put(bairro, cliente.getBairro()); valores.put(cidade, cliente.getCidade()); valores.put(uf, cliente.getUf()); valores.put(d_nascimento, cliente.getData_nasc()); valores.put(cep, cliente.getCep()); valores.put(cpf, cliente.getCpf()); valores.put(email, cliente.getEmail()); valores.put(login, cliente.getLogin()); valores.put(senha, cliente.getSenha()); getWritableDatabase().insert(Tabela, null, valores); //cadastrar cliente no database } public List<Cliente> getLista(){ Cursor c = getWritableDatabase().query(Tabela, Colunas, null, null, null, null, null); List<Cliente> lista = new ArrayList<Cliente>(); while(c.moveToNext()){ Cliente cliente = new Cliente(); cliente.setIdCliente(c.getInt(0)); cliente.setNome(c.getString(1)); cliente.setEndereco(c.getString(2)); cliente.setBairro(c.getString(3)); cliente.setCidade(c.getString(4)); cliente.setUf(c.getString(5)); cliente.setData_nasc(c.getString(6)); cliente.setCep(c.getString(7)); cliente.setCpf(c.getInt(8)); cliente.setEmail(c.getString(9)); cliente.setLogin(c.getString(10)); cliente.setSenha(c.getString(11)); lista.add(cliente); } c.close(); return lista; //metodo listar } public Cliente getClienteById(int posicao){ Cursor c = getWritableDatabase().query(Tabela, Colunas, _idCliente=?, new String[]{ + posicao}, null, null, null); c.moveToFirst(); Cliente cliente = new Cliente(); cliente.setIdCliente(c.getInt(0)); cliente.setNome(c.getString(1)); cliente.setEndereco(c.getString(2)); cliente.setBairro(c.getString(3)); cliente.setCidade(c.getString(4)); cliente.setUf(c.getString(5)); cliente.setData_nasc(c.getString(6)); cliente.setCep(c.getString(7)); cliente.setCpf(c.getInt(8)); cliente.setEmail(c.getString(9)); cliente.setLogin(c.getString(10)); cliente.setSenha(c.getString(11)); c.close(); return cliente; } public void alterarCliente(Cliente cliente){ ContentValues valores = new ContentValues(); valores.put(nome, cliente.getNome()); valores.put(endereco, cliente.getEndereco()); valores.put(bairro, cliente.getBairro()); valores.put(cidade, cliente.getCidade()); valores.put(uf, cliente.getUf()); valores.put(d_nascimento, cliente.getData_nasc()); valores.put(cep, cliente.getCep()); valores.put(cpf, cliente.getCpf()); valores.put(email, cliente.getEmail()); valores.put(login, cliente.getLogin()); valores.put(senha, cliente.getSenha()); getWritableDatabase().update(Tabela, valores, _idCliente=?, new String[]{ + cliente.getIdCliente()}); } public void excluirCliente(int id){ getWritableDatabase().delete(Tabela, _idCliente=?, new String[]{id+}); //excluir cliente } }
21/05/2012
Joel Rodrigues
21/05/2012
Lu
21/05/2012
Lu
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.JQ;
import Classes.Cliente;
import Dao.RepositorioCliente;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import java.util.Random;
/**
*
* @author Peter
*/
public class TelaCadastro extends ListActivity {
Button saButton;
Cursor cursor;
SimpleCursorAdapter AdapterLista;
private RepositorioCliente repositorio;
EditText edit_nome,edit_cpf,edit_data_nasc,edit_endereco,edit_bairro,edit_cep,edit_cidade,edit_fone,edit_email,edit_login,edit_senha;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.telacadastro);
repositorio = new RepositorioCliente(this);
repositorio.open();
// saButton();
}
@ovenride
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.telacadastro);
edit_nome = (EditText) findViewById(R.id.edit_nome);
edit_cpf = (EditText) findViewById(R.id.edit_cpf);
saButton = (bullton) findView ById(R.id.btsalvar);
criarbanco();
//gravarbanco();
btsalvar();
}
public void criarbanco(){
try{
BancoDados = openOrCreatdatabase(jq_bd, MODE_WORLD_READABLE,null);
String SQL = “CREATE TABLE IF NOT EXITs TABLE cadastro(_id_integre primary hey, nome text, fone text)”;
BancoDados.execSQL(sql);
}cacth(Exception + Error){
}
}
public void gravarBanco{
try{
BancoDados = openOrCreatdatabase(jq_bd, MODE_WORLD_READABLE,null);
String SQL = “insert into cadastro(nome,telefone) values ( ‘ ”+nome.getText().toString()” ’, ‘ “+telefone getText().toString()’ ‘’)”;
BancoDados.execSQL(sql);
}catch (Exception + Error){
}
}
private boolean verificarregistro(){
try{
BancoDados = openOrCreatdatabase(jq_bd, MODE_WORLD_READABLE,null);
Cursor = BancoDados.ranquery(“select * from tbcadastro”,null);
if (cursor.getcount()!=0){
cursor.moveToFirst();
return true;
}
else
return false;
}catch (Exception + Error){
return false;
}
finally{
BancoDados.close();
}
}
public carregadados(){
ListView mostrardados = (listview) findViewById(R.findViewById(R.ListViewmostrardados);
if verefica(){
String [] Coluna = newString[] (Key_cadastro;
AdapterLista = new SimpleCursorAdapter(this, R.layout.telacadastro.cursor, coluna, nuw int[] (r.id.tvcarregardados));
Mostradados.setAdapter(AdapterLista);
}
else
//messageAletra(“erro banco”,”falta cadastro”);
}
public void btsalvar(){
Salvar.setOnClickListine(new View. OnClickListine() {
}
}
public void onClick(View argo){
Gravarbanco();
}
}
Clique aqui para fazer login e interagir na Comunidade :)