0
The code of the list:
public class Main2Activity extends Activity {
//Atributos
private SQLiteDatabase bancoDados;
private ArrayAdapter<String> itensAdaptador;
private ArrayList<String> itens;
private ArrayList<Integer>ids;
private Button adicionar;
private EditText txt;
private ListView lista;
private String Name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lista= (ListView)findViewById(R.id.list);
adicionar=(Button)findViewById(R.id.button);
txt=(EditText)findViewById(R.id.txt);
// Criando Banco dados
bancoDados = openOrCreateDatabase("apptarefas", MODE_PRIVATE, null);
//Criando Tabela do banco
bancoDados.execSQL("CREATE TABLE IF NOT EXISTS tarefas(id INTEGER PRIMARY KEY AUTOINCREMENT,tarefa VARCHAR)");
recuperarTarefas();
adicionar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String texto = txt.getText().toString();
salvarTarefa(texto);
txt.setText("");
}
});
//Clicar e remover tarefa
lista.setLongClickable(true);
lista.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
removertarefa(ids.get(position));
return true;
}
});
}
//Metodos
public void salvarTarefa(String texto){
try {
bancoDados.execSQL("INSERT INTO tarefas (tarefa)VALUES('" +texto+ "')");
recuperarTarefas();
}catch (Exception e ){
e.printStackTrace();
}
}
public void recuperarTarefas() {
try {
//Recupera as Tarefas
Cursor cursor = bancoDados.rawQuery("SELECT * FROM tarefas", null);
//Recuperar os ids das colunas
int indiceColunaId = cursor.getColumnIndex("id");
int indiceColunaTarefa = cursor.getColumnIndex("tarefa");
//criar adaptador
ids=new ArrayList<Integer>();
itens= new ArrayList<String>();
itensAdaptador = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_list_item_2,
android.R.id.text2,
itens);
lista.setAdapter(itensAdaptador);
//listar as tarefas
cursor.moveToFirst();
while (cursor != null) {
//Log.i("Resultado", "Tarefa: " + cursor.getString(indiceColunaId));
Log.i("Resultado", "Tarefa: " + cursor.getString(indiceColunaTarefa));
itens.add(cursor.getString(indiceColunaTarefa));
ids.add(Integer.parseInt(cursor.getString(indiceColunaId)));
cursor.moveToNext();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void removertarefa(Integer id){
bancoDados.execSQL("DELETE FROM tarefas WHERE id="+id);
recuperarTarefas();
}
}