Hip*_*lla 5 java android arraylist
请帮忙,我在以下代码中收到以下消息:
listaFinal = (ArrayList<PuntoNota>) getIntent().getSerializableExtra("miLista");
AdapterDatos adapter = new AdapterDatos(this, listaFinal);
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
AdapterDatos:
public AdapterDatos(Context context, ArrayList<PuntoNota> puntoNotaList) {
this.context = context;
this.puntoNotaList = puntoNotaList;
}
Run Code Online (Sandbox Code Playgroud)
该应用程序运行良好,但是我收到以下消息:
未经检查的强制转换:从'java.io.Serializable'到'java.util.ArrayList'更少...(Ctrl + F1)。
关于此代码:(ArrayList)getIntent()。getSerializableExtra(“ myList”); 建议删除或隐藏此消息吗?
根本原因:这是来自 IDE 的警告,getSerializableExtra返回 a 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];
}
};
}
Run Code Online (Sandbox Code Playgroud)
在发送方
ArrayList<PuntoNota> myList = new ArrayList<>();
// Fill data to myList here
...
Intent intent = new Intent();
intent.putParcelableArrayListExtra("miLista", myList);
Run Code Online (Sandbox Code Playgroud)
在接收端
ArrayList<? extends PuntoNota> listaFinal = getIntent().getParcelableArrayListExtra("miLista");
Run Code Online (Sandbox Code Playgroud)
您可以设置警告抑制@SuppressWarnings注释。
例子:
@SuppressWarnings("unchecked")
listaFinal = (ArrayList<PuntoNota>) getIntent().getSerializableExtra("miLista");
Run Code Online (Sandbox Code Playgroud)
这是一个注释,用于抑制有关未经检查的通用操作(不是异常)的编译警告,例如强制转换。它本质上意味着程序员不希望收到有关他在编译特定代码位时已经知道的这些信息的通知。
您可以在此处阅读有关此特定注释的更多信息:
此外,Oracle 在此处提供了一些有关注释使用的教程文档:
正如他们所说,
“在与泛型出现之前编写的遗留代码交互时,可能会出现‘未检查’警告(在题为泛型的课程中讨论过)。”
| 归档时间: |
|
| 查看次数: |
4102 次 |
| 最近记录: |