现在修改代码以反映已接受的解决方案.
现在,这是一个如何将自定义ArrayList传递给DialogFragment的工作示例.
我正在使用newInstance上的Bundle将自定义对象的ArrayList传递给DialogFragment.在newInstance中正确接收了arraylist.对putParcelable的调用执行正常(无错误),但在ArrayList对象的parcelable代码中放置断点表明在设置或获取数据时未调用parcel方法.
我是否正确为ArrayList创建一个LocalityList类并使其成为parcelable,或者Locality类本身是否可以分类?
DialogFragment
/**
* Create a new instance of ValidateUserEnteredLocationLocalitySelectorFragment, providing "localityList"
* as an argument.
*/
public static ValidateUserEnteredLocationLocalitySelectorFragment newInstance(LocalityList localityList) {
ValidateUserEnteredLocationLocalitySelectorFragment fragmentInstance = new ValidateUserEnteredLocationLocalitySelectorFragment();
// Supply location input as an argument.
Bundle bundle = new Bundle();
bundle.putParcelable(KEY_LOCALITY_LIST, localityList);
fragmentInstance.setArguments(bundle);
return fragmentInstance;
}
/**
* Retrieve the locality list from the bundle
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocalityList = getArguments().getParcelable(KEY_LOCALITY_LIST);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { …Run Code Online (Sandbox Code Playgroud) 我从服务器获得了一个json数组response:
[{"id":1, "name":"John", "age": 20},{"id":3, "name":"Tomas", "age": 29}, {"id":12, "name":"Kate", "age": 32}, ...]
Run Code Online (Sandbox Code Playgroud)
我想使用gson将上面的json数据转换为Java List<Person>对象.我尝试了以下方式:
首先,我创建了一个Person.java类:
public class Person{
private long id;
private String name;
private int age;
public long getId(){
return id;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在我的服务类中,我做了以下事情:
//'response' is the above json array
List<Person> personList = gson.fromJson(response, List.class);
for(int i=0; i<personList.size(); i++){
Person p = personList.get(i); //java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast …Run Code Online (Sandbox Code Playgroud) 我想编写一个泛型函数,用Gson反序列化泛型类型List,代码如下:
private <T> List<T> GetListFromFile(String filename)
{
//Read textfile
BufferedReader reader;
String data="";
try
{
reader = new BufferedReader(new FileReader(filename));
data = reader.readLine();
reader.close();
}
catch (FileNotFoundException ex)
{
}
catch (IOException ex)
{
}
if (data == null)
{
List<T> Spiel = new ArrayList<T>();
return Spiel;
}
else
{
//get list with Deserialise
Gson gson = new Gson();
List<T> something = gson.fromJson(data, new TypeToken<List<T>>(){}.getType());
return something;
}
}
Run Code Online (Sandbox Code Playgroud)
但是这段代码不起作用,我得到一个奇怪的结构,但不是我的类型列表
当我使用时:
List<concreteType> something = gson.fromJson(data, new TypeToken<List<T>>(){}.getType());
Run Code Online (Sandbox Code Playgroud)
我的工作我得到了List<concreteType>!! …