gpt4 book ai didi

android - 保存自定义对象的 ArrayList 并向 ArrayList 添加新对象

转载 作者:行者123 更新时间:2023-11-29 17:31:00 24 4
gpt4 key购买 nike

我在将自定义对象的 ArrayList 实例保存在 Activity 中,然后在另一个 Activity 中执行某些操作后检索它时遇到问题。在第一个 Activity (具有 ArrayList)内,有一个启动第二个 Activity 的按钮。在第二个 Activity 中,要求用户创建一个新对象,该对象随后将添加到第一个 Activity 的 ArrayList 中,以便当第二个 Activity 完成时,第一个 Activity 再次显示所有对象的 ListView(包括最后一个一个创建)。我面临的问题是,只有最后创建的对象显示在 ListView 中。

这是第一个 Activity 的代码:

public class CargasMin extends AppCompatActivity implements View.OnClickListener {

RelativeLayout rl_CargasMin;

ImageButton bt_AdDep;
Button bt_CalcCargas;

ListView listView_Dep;

ArrayList<Dependencia> listaDeDependencias = new ArrayList<Dependencia>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.min_cargas);

rl_CargasMin = (RelativeLayout) findViewById(R.id.cargasMinLayout);

bt_AdDep = (ImageButton) findViewById(R.id.bt_AdDep_CargasMin);
bt_CalcCargas = (Button) findViewById(R.id.bt_CalcCargas_CargasMin);
bt_AdDep.setOnClickListener(this);
bt_CalcCargas.setOnClickListener(this);

// This seems not to be working!
if(savedInstanceState == null) { }
else {
listaDeDependencias = savedInstanceState.getParcelableArrayList("key");
}

// Get last object created
Intent intent_de_AdDep = getIntent();
Dependencia dependenciaAAdicionar = (Dependencia) intent_de_AdDep.getParcelableExtra("novaDependencia");
if(dependenciaAAdicionar == null) { }
else {
listaDeDependencias.add(dependenciaAAdicionar);
}

//Cria Adapter pra mostrar dependencias na ListView
DependenciaAdapter adapterDeDependencias = new DependenciaAdapter(this, R.layout.adapter_dependencia, listaDeDependencias);

//Seta Adapter
listView_Dep = (ListView) findViewById(R.id.listView_Dep_CargasMin);
listView_Dep.setAdapter(adapterDeDependencias);
}


@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.bt_AdDep_CargasMin:
Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class);
startActivity(intent_AdDep);
break;
case R.id.bt_CalcCargas_CargasMin:
//
break;
}
}


@Override
protected void onSaveInstanceState(Bundle outState) {
// Aqui se salva a listaDeDependencias quando a Atividade eh momentaneamente fechada.
outState.putParcelableArrayList("key", listaDeDependencias);
super.onSaveInstanceState(outState);
}
}

这是我的自定义类 Dependencia 的代码:

public class Dependencia implements Parcelable {
String nome;
int tipo;

float largura = 0;
float comprimento = 0;
float area = 0;
float perimetro = 0;

// Constructor da classe Dependencia.
public Dependencia(String nomeDep, int tipoDep) {
nome = nomeDep;
tipo = tipoDep;
}

private Dependencia(Parcel in) {
nome = in.readString();
tipo = in.readInt();
largura = in.readFloat();
comprimento = in.readFloat();
area = in.readFloat();
perimetro = in.readFloat();
}

public int describeContents() {
return 0;
}

public void writeToParcel(Parcel out, int flags) {
out.writeString(nome);
out.writeInt(tipo);
out.writeFloat(largura);
out.writeFloat(comprimento);
out.writeFloat(area);
out.writeFloat(perimetro);
}

public static final Parcelable.Creator<Dependencia> CREATOR = new Parcelable.Creator<Dependencia>() {
public Dependencia createFromParcel(Parcel in) {
return new Dependencia(in);
}

public Dependencia[] newArray(int size) {
return new Dependencia[size];
}
};
}

这是第二个 Activity 的代码:

public class AdDep extends AppCompatActivity implements View.OnClickListener {

RelativeLayout rl_AdDep;

EditText et_Nome;
EditText et_Largura;
EditText et_Comprimento;
EditText et_Area;
EditText et_Perimetro;

Spinner spinner_Tipo;
String vetorTipo[];
int tipoEscolhido;

Button bt_AdDep1;
Button bt_AdDep2;

Dependencia novaDependencia;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dep_ad);

rl_AdDep = (RelativeLayout)findViewById(R.id.adDepLayout);

et_Nome = (EditText) findViewById(R.id.et_Nome_AdDep);
et_Largura = (EditText) findViewById(R.id.et_Largura_AdDep);
et_Comprimento = (EditText) findViewById(R.id.et_Comprimento_AdDep);
et_Area = (EditText) findViewById(R.id.et_Area_AdDep);
et_Perimetro = (EditText) findViewById(R.id.et_Perimetro_AdDep);

spinner_Tipo = (Spinner) findViewById(R.id.spinner_Tipo_AdDep);

bt_AdDep1 = (Button) findViewById(R.id.bt_AdDep1);
bt_AdDep2 = (Button) findViewById(R.id.bt_AdDep2);


// Adicionando opcoes no spinner
vetorTipo = new String[5];
vetorTipo[0] = "Banheiro";
vetorTipo[1] = "Varanda";
vetorTipo[2] = "Cozinha/Copa/Serviço/etc.";
vetorTipo[3] = "Sala/Dormitório";
vetorTipo[4] = "Outro";

// Criando ArrayAdapter de strings pro spinner
ArrayAdapter<String> adapterTipo = new ArrayAdapter<String>(AdDep.this, android.R.layout.simple_spinner_item, vetorTipo);

// Setando o Adapter
spinner_Tipo.setAdapter(adapterTipo);

// Valor default do spinner (hint)
spinner_Tipo.setSelection(0);


bt_AdDep1.setOnClickListener(this);
bt_AdDep2.setOnClickListener(this);
}


@Override
public void onClick(View v) {
if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Banheiro"))
tipoEscolhido = 1;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Varanda"))
tipoEscolhido = 2;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Cozinha/Copa/Serviço/etc."))
tipoEscolhido = 3;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Sala/Dormitório"))
tipoEscolhido = 4;
else if(String.valueOf(spinner_Tipo.getSelectedItem()).equals("Outro"))
tipoEscolhido = 5;

novaDependencia = new Dependencia(et_Nome.getText().toString(), tipoEscolhido);

switch(v.getId()) {
case R.id.bt_AdDep1:
novaDependencia.largura = Float.valueOf(et_Largura.getText().toString());
novaDependencia.comprimento = Float.valueOf(et_Comprimento.getText().toString());
break;
case R.id.bt_AdDep2:
novaDependencia.area = Float.valueOf(et_Area.getText().toString());
novaDependencia.perimetro = Float.valueOf(et_Perimetro.getText().toString());
break;
}

AlertDialog.Builder builder2 = new AlertDialog.Builder(v.getContext());
builder2.setMessage("Deseja adicionar T.U.E. nesta dependência?").setPositiveButton("Sim", dialogClickListener).setNegativeButton("Não", dialogClickListener).show();
}

// Objeto tipo dialog criado para perguntar se usario deseja inserir TUEs
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
Intent intent_NovaDep_CargasMin = new Intent(AdDep.this, CargasMin.class);
intent_NovaDep_CargasMin.putExtra("novaDependencia", novaDependencia);
startActivity(intent_NovaDep_CargasMin);
break;
}
}
};

}

如果有人知道如何解决这个问题,请分享。谢谢。

最佳答案

问题是您正在从 AdDep Activity 启动 CargasMin Activity 的新实例。您的 AdDep Activity 应该刚刚完成并将结果返回到返回堆栈上的 CargasMin Activity 的现有实例,以便您也可以查看所有之前的列表数据。

要从 AdDep 中检索新列表项作为结果,请使用 startActivityForResult()

case R.id.bt_AdDep_CargasMin:
Intent intent_AdDep = new Intent(CargasMin.this, AdDep.class);
startActivityForResult(intent_AdDep, ADD_DEP_REQUEST);
break;

ADD_DEP_REQUEST 只是一个请求代码常量

public static final int ADD_DEP_REQUEST = 1;

现在,当 AdDep 收集完数据后,它会返回新的数据项作为结果。

case DialogInterface.BUTTON_NEGATIVE:
Intent result = new Intent();
result.putExtra("novaDependencia", novaDependencia);
setResult(Activity.RESULT_OK, result);
finish();
break;

您的主要 CargasMin Activity 随后将接收新数据项作为

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ADD_DEP_REQUEST) {
if (resultCode == RESULT_OK) {
// Get last object created
Dependencia dependenciaAAdicionar =
(Dependencia) data.getParcelableExtra("novaDependencia");
if(dependenciaAAdicionar != null){
listaDeDependencias.add(dependenciaAAdicionar);
// Refresh Adapter pra mostrar dependenciaAAdicionar na ListView
adapterDeDependencias.notifyDataSetChanged();
}
}
}
}

请注意,listaDeDependenciasadapterDeDependencias 已更改为 Activity 的实例成员。

如果您将数据持久化到某个存储(例如在文件或数据库中),您当前的方法会奏效,但仍然不建议创建 CargasMin 的新实例,因为返回堆栈就足够了。

关于android - 保存自定义对象的 ArrayList 并向 ArrayList 添加新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33007021/

24 4 0