gpt4 book ai didi

My checkbox is not saving when closing and opening the application(关闭和打开应用程序时,我的复选框未保存)

转载 作者:bug小助手 更新时间:2023-10-24 20:39:37 25 4
gpt4 key购买 nike



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

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)

Linha.xml(其中是复选框)


<?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>

更多回答

Instead of pasting your entire code here, your first step when debugging should be to make a minimum example - for example a new project with a single activity and a single check box, or if the list is necessary a simple list with one item and one check box - and use that to try out the code patterns you want to use. Then, if you still can't get it working there you can share the minimal example here and describe what is happening.

与将整个代码粘贴到此处不同,调试时的第一步应该是生成最少的示例--例如,具有单个活动和单个复选框的新项目,或者如果列表是必要的,则是具有一个项和一个复选框的简单列表--并使用该列表来测试您想要使用的代码模式。然后,如果你仍然不能让它在那里工作,你可以在这里分享最小的例子,并描述正在发生的事情。

优秀答案推荐

It seems like you are trying to save the state of a checkbox using SharedPreferences, but the code provided doesn't show how the checkboxes are being added to your ListView or how you are updating their state. Here are some steps you can follow to save and restore the state of checkboxes in your ListView:

您似乎正在尝试使用SharedPreferences保存复选框的状态,但提供的代码没有显示如何将复选框添加到您的ListView中,或者您如何更新其状态。以下是在ListView中保存和恢复复选框状态的一些步骤:



  1. First, make sure you have a model class to represent your list items (in this case, Tarefa) that includes a property for the checkbox state (e.g., isChecked).



  2. Update your ListaTarefaAdapter to work with this model class and bind the checkbox state to the actual checkboxes in your list item layout (linha.xml).



  3. When a checkbox state changes, update the corresponding property in your model class.



  4. In your onCreate method, after you initialize your adapter and ListView, set the adapter on the ListView.



  5. In your check method, you can use SharedPreferences to restore the checkbox state when the activity is created.



  6. In your CompoundButton.OnCheckedChangeListener, update the model class with the new state and save it in SharedPreferences.




Here's a modified version of your MainActivity class to demonstrate these steps:

以下是MainActivity类的修改版本,以演示这些步骤:


import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
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();
arrayTarefa = new ListaTarefaAdapter(getApplicationContext(), item);
listar.setAdapter(arrayTarefa);
check();
}

private void mapearXML() {
// Your existing code for mapping views
}

private void verificar() {
// Your existing code for database initialization
}

private void check() {
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
boolean isChecked = sharedPreferences.getBoolean("checkBoxState", false);
// Set the initial checkbox state here
// You need to determine which item's checkbox you want to set based on your logic
// For now, I'm assuming it's the first item in the list
if (!item.isEmpty()) {
item.get(0).setChecked(isChecked);
arrayTarefa.notifyDataSetChanged();
}
}

private void click() {
// Your existing code for button click and item click listeners
}

// Rest of your MainActivity code...

}

In this modified code, I've added comments to guide you on where to set and update the checkbox state based on your logic. You'll need to adapt this code according to your specific requirements and how you handle checkboxes in your ListaTarefaAdapter. The key is to update the checkbox state in your model class (Tarefa) and notify the adapter of the changes so that it reflects the correct state in the ListView.

在修改后的代码中,我添加了注释,以指导您根据逻辑在何处设置和更新复选框状态。您需要根据您的特定需求以及如何处理ListaTarefaAdapter中的复选框来调整此代码。关键是更新模型类(Tarefa)中的复选框状态,并将更改通知适配器,以便它在ListView中反映正确的状态。


Good Luck.

祝好运。


更多回答

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com