Exemplo completo - Neri |
Top Previous |
Projeto Tela
DataBaseActivity.java
package com.banco;
import android.app.Activity; import android.app.AlertDialog; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import android.content.DialogInterface; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase;
public class DataBaseActivity extends Activity {
private final String NOME_BASE = "pessoas2.db"; private final String TB_PESSOAS = "tb_pessoas"; private final String CAMPO_ID = "_id"; private final String CAMPO_NOME = "nome"; private final String CAMPO_CIDADE = "cidade"; private final String CAMPO_FONE = "fone"; private int _id = 0; private SharedPreferences mPrefs; // manter o id mesmo com o fechamento do // aplicativo. SQLiteDatabase bancoDados; Cursor cursor;
// tela EditText edNome, edFone, edCidade; Button btNovo, btExcluir, btGravar; ListView lvLista; SimpleCursorAdapter AdapterLista;
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }
@Override protected void onResume() { super.onResume(); abreouCriaBanco();
// associar edNome = (EditText) findViewById(R.id.edNome); edFone = (EditText) findViewById(R.id.edFone); edCidade = (EditText) findViewById(R.id.edCidade);
btNovo = (Button) findViewById(R.id.btNovo); btExcluir = (Button) findViewById(R.id.btExcluir); btGravar = (Button) findViewById(R.id.btGravar);
lvLista = (ListView) findViewById(R.id.lvDados);
// eventos AssociarEventos();
buscarDados();
// carrega ultimo id utilizado SharedPreferences mPrefs = getSharedPreferences("ConfigCadastro", MODE_PRIVATE); _id = mPrefs.getInt("ultimo_id", 0); }
@Override protected void onPause() { super.onPause(); fecharBanco();
// salva o ultimo id utilizado mPrefs = getSharedPreferences("ConfigCadastro", MODE_PRIVATE); SharedPreferences.Editor confEditor = mPrefs.edit(); confEditor.putInt("ultimo_id", _id); confEditor.commit(); }
public void abreouCriaBanco() { try { bancoDados = openOrCreateDatabase(NOME_BASE, MODE_WORLD_WRITEABLE, null);
String sql = "CREATE TABLE IF NOT EXISTS " + TB_PESSOAS + " (" + CAMPO_ID + " INTEGER PRIMARY KEY, " + CAMPO_NOME + " TEXT, " + CAMPO_CIDADE + " TEXT, " + CAMPO_FONE + " TEXT);"; bancoDados.execSQL(sql);
Toast.makeText(this, "Banco criado/aberta com sucesso!", Toast.LENGTH_LONG).show(); } catch (Exception erro) { Toast.makeText(this, erro.getMessage(), Toast.LENGTH_LONG).show(); } }
public void AssociarEventos() { btNovo.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { limparCampos(); } });
btExcluir.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { AlertDialog.Builder builder = new AlertDialog.Builder( DataBaseActivity.this); builder.setMessage("Excluir o registro?") .setPositiveButton("Sim", // escolheu sim... new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { excluirRegistro(); limparCampos(); } }) // escolheu não .setNegativeButton("Não", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show();
} }); btGravar.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { if (_id == 0) inserirRegistro(); else atualizarRegistro(); } });
// ao clicar na listView... lvLista.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int Posicao, long arg3) { // obtem o cursor a partir da Posicao selecionada na listView
Cursor mycursor = (Cursor) lvLista.getItemAtPosition(Posicao);
// a partir do cursor obtem o "_id" do registro _id = Integer.parseInt(mycursor.getString(mycursor .getColumnIndex(CAMPO_ID))); carregarDadosEdicao(); } }); }
public void carregarDadosEdicao() { try { Cursor c = bancoDados.rawQuery("SELECT * FROM " + TB_PESSOAS + " WHERE " + CAMPO_ID + "=" + String.valueOf(_id), null);
if (c.getCount() > 0) { c.moveToFirst(); edNome.setText(c.getString(cursor.getColumnIndex(CAMPO_NOME))); edFone.setText(c.getString(cursor.getColumnIndex(CAMPO_FONE))); edCidade.setText(c.getString(cursor .getColumnIndex(CAMPO_CIDADE))); edNome.requestFocus(); btExcluir.setVisibility(View.VISIBLE); }
} catch (Exception erro) { Toast.makeText(this, "Erro ao buscar dados\n" + erro.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void fecharBanco() { try { bancoDados.close(); } catch (Exception erro) { Toast.makeText(this, "Erro ao fechar banco\n" + erro.getMessage(), Toast.LENGTH_LONG).show(); } }
private boolean buscarDados() { try { cursor = bancoDados.rawQuery("SELECT * FROM " + TB_PESSOAS + " ORDER BY " + CAMPO_NOME, null); // bancoDados.query(TB_PESSOAS, new String[] { CAMPO_ID, CAMPO_NOME, // CAMPO_FONE, CAMPO_CIDADE }, null, null, null, null, // CAMPO_NOME);
if (cursor.getCount() == 0) { Toast.makeText(this, "Base vazia", Toast.LENGTH_LONG).show(); } else { cursor.moveToFirst(); Toast.makeText(this, "Registros: " + String.valueOf(cursor.getCount()), Toast.LENGTH_LONG).show(); CarregarListView(); return true; }
} catch (Exception erro) { Toast.makeText(this, "Erro ao buscar dados\n" + erro.getMessage(), Toast.LENGTH_LONG).show();
} return false; }
public void limparCampos() { edNome.setText(""); edFone.setText(""); edCidade.setText(""); _id = 0; btExcluir.setVisibility(View.INVISIBLE); }
public void CarregarListView() { // as colunas (nomes) é um array de string String[] Colunas = new String[] { CAMPO_ID, CAMPO_NOME }; // o Adapter vincula o xml com o cursor e com as "EditTexts" dentro // da xml AdapterLista = new SimpleCursorAdapter(this, R.layout.mostrabanco, cursor, Colunas, new int[] { R.id.edListNome, R.id.edListTelefone }); // associa o adaptar ao listView do main.xml lvLista.setAdapter(AdapterLista); }
public void inserirRegistro() { try {
String sql = "INSERT INTO " + TB_PESSOAS + " (" + CAMPO_NOME + "," + CAMPO_FONE + "," + CAMPO_CIDADE + ") values (" + "'" + edNome.getText().toString() + "', " + "'" + edFone.getText().toString() + "', " + "'" + edCidade.getText().toString() + "')"; bancoDados.execSQL(sql); buscarDados(); Toast.makeText(this, edNome.getText().toString() + " gravou ok", Toast.LENGTH_LONG).show();
} catch (Exception erro) { Toast.makeText(this, "Erro ao gravar dados\n" + erro.getMessage(), Toast.LENGTH_LONG).show();
} }
public void atualizarRegistro() { try {
String sql = "UPDATE " + TB_PESSOAS + " SET " + CAMPO_NOME + "='" + edNome.getText().toString() + "', " + CAMPO_FONE + "='" + edFone.getText().toString() + "', " + CAMPO_CIDADE + "='" + edCidade.getText().toString() + "'" + " WHERE " + CAMPO_ID + "=" + String.valueOf(_id); bancoDados.execSQL(sql); buscarDados(); Toast.makeText(this, edNome.getText().toString() + " atualizou ok", Toast.LENGTH_LONG).show();
} catch (Exception erro) { Toast.makeText(this, "Erro ao gravar dados\n" + erro.getMessage(), Toast.LENGTH_LONG).show(); } }
public void excluirRegistro() { try {
String sql = "DELETE FROM " + TB_PESSOAS + " WHERE " + CAMPO_ID + "=" + String.valueOf(_id); bancoDados.execSQL(sql); buscarDados(); Log.i("Exclusao", edNome.getText().toString() + " excluiu ok"); } catch (Exception erro) { Toast.makeText(this, "Erro ao excluir dados\n" + erro.getMessage(), Toast.LENGTH_LONG).show(); } } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Nome" />
<EditText android:id="@+id/edNome" android:layout_width="fill_parent" android:layout_height="wrap_content" >
<requestFocus /> </EditText>
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Fone" />
<EditText android:id="@+id/edFone" android:layout_width="fill_parent" android:layout_height="wrap_content" > </EditText>
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Cidade" />
<EditText android:id="@+id/edCidade" android:layout_width="fill_parent" android:layout_height="wrap_content" > </EditText>
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:gravity="center_horizontal" android:layout_height="wrap_content" >
<Button android:id="@+id/btNovo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Novo" />
<Button android:id="@+id/btExcluir" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Excluir" />
<Button android:id="@+id/btGravar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Gravar" />
</LinearLayout>
<ListView android:id="@+id/lvDados" android:layout_width="fill_parent" android:layout_height="wrap_content" > </ListView>
</LinearLayout>
mostrabanco.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" >
<TextView android:id="@+id/edListNome" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="@+id/edListTelefone" android:layout_width="fill_parent" android:textSize="10sp" android:layout_height="wrap_content"/> </LinearLayout>
|