I'm trying to get the box to be saved when I open the application again, but when I close and open it it always comes back empty. I've faced many pointer errors trying to resolve this, I've tried creating directly in the onCreate method, but nothing works.
MainActivity
package br.mateus.appTarefas;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
import br.mateus.appTarefas.model.ListaTarefaAdapter;
import br.mateus.appTarefas.model.Tarefa;
import br.mateus.appTarefas.persistance.TarefaBD;
import br.mateus.appTarefas.persistance.TarefaDAO;
public class MainActivity extends AppCompatActivity{
private EditText titulo;
private EditText descricao;
private ImageButton botaoSalvar;
private ListView listar;
private List<Tarefa>item;
private ListaTarefaAdapter arrayTarefa;
private TarefaDAO dao;
private Tarefa t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.Theme_App);
setContentView(R.layout.activity_main);
mapearXML();
verificar();
click();
check();
arrayTarefa = new ListaTarefaAdapter(getApplicationContext(),item);
listar.setAdapter(arrayTarefa);
}
private void mapearXML(){
titulo = findViewById(R.id.idTitulo);
descricao = findViewById(R.id.idDescricao);
botaoSalvar = findViewById(R.id.idSalvar);
listar = findViewById(R.id.idLista);
}
private void verificar(){
if(dao==null){
dao = new TarefaBD(this);
}
item=dao.listar();
}
private void check(){
View checkLayout = getLayoutInflater().inflate(R.layout.linha,null);
CheckBox check = checkLayout.findViewById(R.id.idCheckBox);
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
boolean isChecked = sharedPreferences.getBoolean("checkBoxState", false);
check.setChecked(isChecked);
check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor = getSharedPreferences("MyPrefs", MODE_PRIVATE).edit();
editor.putBoolean("checkBoxState", isChecked);
editor.apply();
}
});
}
private void click(){
botaoSalvar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("MainActivitya","Item clicado");
String tituloTarefa = titulo.getText().toString().trim();
String descricaoTarefa = descricao.getText().toString().trim();
if (tituloTarefa.isEmpty() ) {
titulo.setError("Este campo não pode estar vazio.");
}else if(descricaoTarefa.isEmpty()){
descricao.setError("Este campo não pode estar vazio.");
}else{
if (t == null) {
t = new Tarefa();
}
t.setTitulo(tituloTarefa);
t.setDescricao(descricaoTarefa);
if (t.getId() == null) {
dao.salvar(t);
} else {
dao.editar(t);
}
limparCampos();
atualizarItens();
}
}
});
listar.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
final Tarefa tarefaSelecionada = item.get(position);
LinearLayout itemLayout = view.findViewById(R.id.idItem); // Substitua "R.id.itemLayout" pelo ID correto do seu LinearLayout no arquivo linha.xml
itemLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mostrarDialogoEditarExcluir(tarefaSelecionada);
}
});
}
});
};
private void mostrarDialogoEditarExcluir(final Tarefa tarefa) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
dialogBuilder.setTitle("Opções");
dialogBuilder.setMessage("Escolha uma opção para a tarefa:");
dialogBuilder.setPositiveButton("Editar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
abrirDialogoEditar(tarefa);
}
});
dialogBuilder.setNegativeButton("Excluir", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mostrarDialogoConfirmacaoExcluir(tarefa);
}
});
dialogBuilder.setNeutralButton("Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Ação a ser realizada quando o botão "Cancelar" for clicado
}
});
dialogBuilder.create().show();
}
private void abrirDialogoEditar(final Tarefa tarefa) {
AlertDialog.Builder editarDialogBuilder = new AlertDialog.Builder(MainActivity.this);
editarDialogBuilder.setTitle("Editar Tarefa");
// Inflar o layout do diálogo de edição
View editarView = getLayoutInflater().inflate(R.layout.dialog_editar, null);
editarDialogBuilder.setView(editarView);
final EditText editarTitulo = editarView.findViewById(R.id.idTitulo);
final EditText editarDescricao = editarView.findViewById(R.id.idDescricao);
editarTitulo.setText(tarefa.getTitulo());
editarDescricao.setText(tarefa.getDescricao());
editarDialogBuilder.setPositiveButton("Salvar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String novoTitulo = editarTitulo.getText().toString();
String novaDescricao = editarDescricao.getText().toString();
// Atualize a tarefa com os novos valores aqui
tarefa.setTitulo(novoTitulo);
tarefa.setDescricao(novaDescricao);
// Atualize a tarefa no banco de dados
dao.editar(tarefa);
// Atualize a lista de tarefas na interface do usuário
atualizarItens();
}
});
editarDialogBuilder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Ação a ser realizada quando o botão "Cancelar" for clicado
}
});
editarDialogBuilder.create().show();
}
private void mostrarDialogoConfirmacaoExcluir(final Tarefa tarefa) {
AlertDialog.Builder confirmarExclusaoDialogBuilder = new AlertDialog.Builder(MainActivity.this);
confirmarExclusaoDialogBuilder.setTitle("Confirmar Exclusão");
confirmarExclusaoDialogBuilder.setMessage("Tem certeza de que deseja excluir esta tarefa?");
confirmarExclusaoDialogBuilder.setPositiveButton("Excluir", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Execute a exclusão da tarefa aqui
dao.remove(tarefa);
// Atualize a lista de tarefas na interface do usuário
atualizarItens();
}
});
confirmarExclusaoDialogBuilder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Ação a ser realizada quando o botão "Cancelar" for clicado
}
});
confirmarExclusaoDialogBuilder.create().show();
}
private void atualizarItens(){
item.clear();
item.addAll(dao.listar());
arrayTarefa.notifyDataSetChanged();
}
private void limparCampos(){
titulo.setText(" ");
descricao.setText(" ");
t=null;
}
public void cancelar(View view){
AlertDialog.Builder cancela = new AlertDialog.Builder(this);
cancela.setTitle("Deseja mesmo sair?");
cancela.setPositiveButton("Sair", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
cancela.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
cancela.create().show();
}
}
activity_main xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/idPrincipal"
android:layout_height="match_parent"
android:background="@color/azulescuro"
>
<ListView
android:id="@+id/idLista"
android:layout_width="401dp"
android:layout_height="331dp"
android:layout_marginTop="392dp"
android:textFilterEnabled="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<ImageButton
android:id="@+id/idCancelar"
android:layout_width="77dp"
android:layout_height="120dp"
android:layout_marginStart="4dp"
android:layout_marginBottom="8dp"
android:backgroundTint="#00FFFFFF"
android:contentDescription="Sair"
android:onClick="cancelar"
android:src="@drawable/sair"
app:layout_constraintBottom_toTopOf="@+id/idTitulo"
app:layout_constraintStart_toEndOf="@+id/idSalvar" />
<ImageButton
android:id="@+id/idSalvar"
android:layout_width="67dp"
android:layout_height="86dp"
android:layout_gravity="center"
android:layout_marginStart="272dp"
android:layout_marginBottom="24dp"
android:backgroundTint="#00FFFFFF"
android:contentDescription="Adicionar"
android:scaleType="fitCenter"
android:src="@drawable/adicionar"
app:layout_constraintBottom_toTopOf="@+id/idTitulo"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="@+id/idTitulo"
android:layout_width="396dp"
android:layout_height="73dp"
android:layout_marginStart="4dp"
android:layout_marginTop="116dp"
android:ems="10"
android:hint="Título"
android:inputType="text"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/idDescricao"
android:layout_width="394dp"
android:layout_height="142dp"
android:layout_marginStart="4dp"
android:layout_marginTop="36dp"
android:ems="10"
android:hint="Descrição"
android:inputType="text"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/idTitulo" />
</androidx.constraintlayout.widget.ConstraintLayout>
linha.xml (where is the checkbox)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/idItem"
android:layout_width="400dp"
android:layout_height="50dp"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="@+id/idCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textTitulo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Texto da Linha 1" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textDescricao"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="30dp"
android:text="Texto da Linha 2" />
</LinearLayout>
</LinearLayout>
Aucun commentaire:
Enregistrer un commentaire