在我的应用程序中,我试图通过意图将可序列化的对象传递给另一个活动。意图不是完全由我创建的,它是通过搜索建议创建和传递的。可串行化的对象意图以字符串形式返回
在搜索建议的内容提供者中,创建对象并将其放置在MatrixCursor的SUGGEST_COLUMN_INTENT_EXTRA_DATA
列中。但是,在接收活动中,我调用getIntent().getSerializableExtra(SearchManager.EXTRA_DATA_KEY)
时,返回的对象是String类型,我无法将其转换为原始对象类。
我试着为我的对象制作一个可打包的包装,它调用out.writeSerializable(...)
,然后用它代替,但是同样的事情发生了。
返回的字符串就像一个普通的Object toString(),即[email protected]
,所以我假设toString()被调用的地方我没有任何控制。
希望我只是想念一件简单的事情。谢谢您的帮助!
编辑:我的一些代码
这是在充当搜索权威内容提供商:
//These are the search suggestion columns
private static final String[] COLUMNS = {
"_id", // mandatory column
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA
};
//This places the serializable or parcelable object (and other info) into the search suggestion
private Cursor getSuggestions(String query, String[] projection) {
List<Widget> widgets = WidgetLoader.getMatches(query);
MatrixCursor cursor = new MatrixCursor(COLUMNS);
for (Widget w : widgets) {
cursor.addRow(new Object[] {
w.id
w.name
w.data //This is the MyAwesomeClass object I'm trying to pass
});
}
return cursor;
}
这是在接收搜索建议的活动:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Object extra = getIntent().getSerializableExtra(SearchManager.EXTRA_DATA_KEY);
//extra.getClass() returns String, when it should return MyAwesomeClass, so this next line throws a ClassCastException and causes a crash
MyAwesomeClass mac = (MyAwesomeClass)extra;
...
}