使用Intent / Bundle在活动之间传递TreeMap

时间:2013-05-21 13:43:48

标签: android android-intent treemap

我正在尝试在一个活动和另一个活动之间传递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);
}
Log Cat: 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中出来的任何想法?为什么只在两个活动之间?

由于

0 个答案:

没有答案