我正在尝试在一个活动和另一个活动之间传递 TreeMap。TreeMap 的类型为 TreeMap>
我尝试制作 Trip Serializable 和 Parcelable 但我无法让它工作。我还在 onSaveInstanceState 期间将地图添加到捆绑包中,并在 onRestoreInstanceState 期间成功恢复它,但在活动之间没有。
这是Trip的定义
package stations;
import java.io.IOException;
import java.io.Serializable;
import android.text.format.Time;
public class Trip implements Serializable {
private static final long serialVersionUID = 1L;
Time m_time = new Time();
public Trip()
{
m_time.setToNow();
}
private void writeObject(java.io.ObjectOutputStream out)
throws IOException {
out.writeLong(m_time.toMillis(false));
}
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
m_time = new Time();
m_time.set(in.readLong());
}
}
这部分效果很好:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable(PERSONAL_SET_STR, m_personalSet);
super.onSaveInstanceState(savedInstanceState);
}
@SuppressWarnings("unchecked")
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
m_personalSet = (TreeMap<Integer,Vector<Trip>>)savedInstanceState.getSerializable(PERSONAL_SET_STR);
Toast.makeText(this, "on Restore " + m_personalSet.size(), Toast.LENGTH_SHORT).show();
}
这是我开始第二个活动的方式
Intent intent = new Intent(this, SecondActivity.class);
Bundle b = new Bundle();
b.putSerializable(PERSONAL_SET_STR, m_personalSet);
intent.putExtras(b);
startActivity(intent);
这是 SecondActivity 的 OnCreate
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
//This next line throws an exception
m_personalSet = (TreeMap<Integer,Vector<Trip>>)b.getSerializable(FirstActivity.PERSONAL_SET_STR);
}
日志猫:05-21 16:34:24.086:E/AndroidRuntime(17343):java.lang.RuntimeException:无法启动活动 ComponentInfo{com.me.atme/analysis.SecondClass}:java.lang.ClassCastException:java .util.HashMap 不能转换为 java.util.TreeMap
任何想法为什么它作为HashMap而不是TreeMap从Bundle中出来?为什么只在两个活动之间?
谢谢