gpt4 book ai didi

java - 未经检查将 java.io.Serializable 转换为 java.util.ArrayList

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:17:28 25 4
gpt4 key购买 nike

请帮忙,我在以下代码中收到以下消息:

listaFinal = (ArrayList<PuntoNota>) getIntent().getSerializableExtra("miLista");

AdapterDatos adapter = new AdapterDatos(this, listaFinal);

PuntoNota.java

public class PuntoNota implements Serializable{
private String punto;
private String nota;

public PuntoNota (String punto, String nota){
this.punto = punto;
this.nota = nota;
}

public String getPunto(){
return punto;
}


public String getNota(){
return nota;
}

}

适配器数据:

public AdapterDatos(Context context, ArrayList<PuntoNota> puntoNotaList) {
this.context = context;
this.puntoNotaList = puntoNotaList;
}

应用程序运行良好,但我收到以下消息:

Unchecked cast: 'java.io.Serializable' to 'java.util.ArrayList ' less ... (Ctrl + F1).
about this code: (ArrayList ) getIntent (). getSerializableExtra ("myList"); will it be advisable to delete or hide this message?

最佳答案

根本原因:这是来自 IDE 的警告,getSerializableExtra返回 Serializable ,并且您正在尝试转换为 ArrayList<PuntoNota> .如果程序无法将其转换为您期望的类型,它可能会在运行时抛出 ClassCastException

解决方案:在 android 中传递一个用户定义的对象,你的类应该实现 Parcelable而不是 Serializable界面。

class PuntoNota implements Parcelable {
private String punto;
private String nota;

public PuntoNota(String punto, String nota) {
this.punto = punto;
this.nota = nota;
}

protected PuntoNota(Parcel in) {
punto = in.readString();
nota = in.readString();
}

public String getPunto() {
return punto;
}

public String getNota() {
return nota;
}

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(punto);
dest.writeString(nota);
}

public static final Creator<PuntoNota> CREATOR = new Creator<PuntoNota>() {
@Override
public PuntoNota createFromParcel(Parcel in) {
return new PuntoNota(in);
}

@Override
public PuntoNota[] newArray(int size) {
return new PuntoNota[size];
}
};
}

发送端

ArrayList<PuntoNota> myList = new ArrayList<>();
// Fill data to myList here
...
Intent intent = new Intent();
intent.putParcelableArrayListExtra("miLista", myList);

在接收端

ArrayList<? extends PuntoNota> listaFinal = getIntent().getParcelableArrayListExtra("miLista");

关于java - 未经检查将 java.io.Serializable 转换为 java.util.ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51805648/

25 4 0