// this is the method referred to below (in activity 1)
public ArrayList<MatchEntry[]> getAllMatchEntries()
{
ArrayList<MatchEntry[]> result = new ArrayList<MatchEntry[]>();
for(int i = 0; i < this.size(); i++)
{
result.add(this.get(i).getMatchInfo());
}
return result;
}
/**
* stores information about a single match
*/
public class MatchEntry implements Serializable
{...}
// Activity 1 - bundling
ArrayList<MatchEntry[]> allMatchEntries = _hadiths.getAllMatchEntries();
b.putSerializable("allMatchEntries", allMatchEntries);
Intent i = new Intent(...);
i.putExtras(b);
// Activity 2 - de-bundling
private ArrayList<MatchEntry[]> _allMatchEntries;
_allMatchEntries = (ArrayList<MatchEntry[]>) bundle.getSerializable("allMatchEntries");
// in fragment adapter, this is where the error occurs
class MyFragmentAdapter extends FragmentPagerAdapter
{
...
@Override
public Fragment getItem(int position)
{
// java.lang.ClassCastException: java.lang.Object[] cannot be cast to com.a.b.MatchEntry[]
MatchEntry[] entries = (_allMatchEntries != null) ? _allMatchEntries.get(position) : null;
}
}
// this is the fragment
public class MyFragment extends Fragment
{
public static HadithFragment newInstance(int id, MatchEntry[] matchEntries)
{
MyFragment fm = new MyFragment();
Bundle args = new Bundle();
args.putInt("_id", id);
args.putSerializable("matchEntries", matchEntries); // store for onCreateView
fm.setArguments(args);
return fm;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// handle highlighting
MatchEntry[] _matchEntries = (MatchEntry[]) getArguments().getSerializable("matchEntries");
if(_matchEntries != null && _matchEntries.length > 0)
{
...
}
}
说真的,我看不出我做错了什么。
编辑:
我一直用来查看发生了什么的调试器在反序列化时显示了这样的结构:
ArrayList<Object[]>
Object[1]
Object[1]
Object[2]
Object[1]
Object[2]
MatchEntry
MatchEntry
这很令人困惑,因为我知道我序列化了一个 ArrayList<MatchEntry[]>
正如您在我的代码中看到的那样,为什么它有一个 ArrayList<Object[]>
在反序列化?基本上这就是我整个问题的要点。
最佳答案
嗯,问题是您不能将 Object[] 数组转换为任何特定数组。这是 Java 特定的属性。
你必须在一个循环中转换每个元素,或者你可以这样缩短它:
Object[] temp = _allMatchEntries.get(position)
MatchEntry[] target = new MatchEntry[temp.length]();
System.arraycopy(temp, 0, target, 0, a.length);
不知何故类型丢失了,我不知道它的原因,但它有点奇怪。正如我所说,它可以与 ArrayList
或者,您可以使用 ArrayList< ArrayList< MatchEntry>>。这会起作用,至少我已经测试过了。
关于java - 反序列化包并转换回实际类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21032831/