gpt4 book ai didi

android - 如何将 List 从 Activity 传递到 fragment

转载 作者:搜寻专家 更新时间:2023-11-01 07:44:52 25 4
gpt4 key购买 nike

这是我使用数据库助手类从数据库中检索数据的代码

 public List<Hospitals> getHospitals(Context context){
Hospitals hospitals = null;
List<Hospitals> hospitalList = new ArrayList<>();
openDatabase(context);
Cursor cursor = database.rawQuery("SELECT * FROM buildings WHERE category_id = 1", null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
hospitals = new Hospitals(cursor.getInt(0), cursor.getString(1), cursor.getFloat(2), cursor.getFloat(4));
hospitalList.add(hospitals);
cursor.moveToNext();
}
cursor.close();
closeDatabase();

return hospitalList;
}

这是我的类(class)医院

public class Hospitals {
private int id;
private String name;
private Float latitude;
private Float longhitude;

public Hospitals(int id, String name, Float latitude, Float longhitude ){
this.id = id;
this.name = name;
this.latitude = latitude;
this.longhitude = longhitude;

}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Float getLatitude() {
return latitude;
}

public void setLatitude(Float latitude) {
this.latitude = latitude;
}

public Float getLonghitude() {
return longhitude;
}

public void setLonghitude(Float longhitude) {
this.longhitude = longhitude;
}

这是我在主要 Activity 中将 List<> 传递给 fragment 的代码

List<Hospitals> result = databaseHelper.getHospitals(this);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("valuesArray", result);
GmapFragment gmapFragment = new GmapFragment();
gmapFragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.mainLayout, gmapFragment).commit();

我在 putParcelableArrayList() 中得到了第二个参数 - 第二个参数类型错误。找到:'java.util.List',需要:'java.util.ArrayList

如何解决该错误?

最佳答案

Wrong 2nd argument type. Found: 'java.util.List', required: 'java.util.ArrayList

首先将LIST转换为ARRAYLIST

 List<Hospitals> result = databaseHelper.getHospitals(this);
ArrayList<Hospitals> al_HOSPITAL = new ArrayList<>(result.size());
al_HOSPITAL.addAll(result);

然后

Bundle bundle = new Bundle();
bundle.putSerializable("valuesArray", al_HOSPITAL);

你应该使用 Parcelable .

AFAIK 使用 Parcelable 优于 Serializable

  • Parcelable耗时且容易出错的过程

Interface for classes whose instances can be written to and restored from a Parcel. Classes implementing the Parcelable interface must also have a non-null static field called CREATOR of a type that implements the Parcelable.Creator interface.

public class Hospitals implements Parcelable {

最后 Clean-Rebuild-Run 。希望这会有所帮助。

关于android - 如何将 List<NameOfClassObject> 从 Activity 传递到 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46752669/

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