Kotlin Android:如何在没有未经检查的强制转换警告的情况下通过意图传递 ArrayList of Seria



我正在创建一个这样的Intent

public void showThings(ArrayList<Thing> things) {
Intent intent = new Intent(this, ThingActivity.class);
intent.putExtra(THINGS, things);
startActivity(intent);
}

然后在ThingActivity我想得到ArrayList<Thing>

class ThingActivity {
var things: ArrayList<Thing>? = null
override fun onCreate(savedInstanceState: Bundle?) {
things = intent.extras.getSerializable(OtherActivity.THINGS) as? ArrayList<Thing>
}

不幸的是,我似乎无法弄清楚如何在不触发"未经检查的投射"警告的情况下投射到适当的类型。有没有办法在(以某种方式意外地(强制转换失败时优雅地设置为null

附加?: return null似乎不像我在其他地方看到的那样有效

由于 Java 泛型在运行时的工作方式,正在发生未经检查的强制转换警告。由于类型擦除,在运行时,列表的类型只是List,而不是List<Thing>。这意味着强制转换被认为是不安全的,即使人类很有可能查看代码并发现没有问题。

虽然我同意你的观点,即抑制警告并不理想,但在这种情况下,我认为这很好。

但是,最好的解决方案是在Thing上实现Parcelable接口。这样,当您想要通过意图传递List<Thing>时,您可以编写:

intent.putParcelableArrayListExtra(THINGS, things)

当您想读回它时:

things = intent.extras.getParcelableArrayListExtra(OtherActivity.THINGS)

这些都不会导致编译器警告。

作为Ben P的答案的替代方案,你可以使用Gson。

假设Things只是一个数据类(包含一堆变量(,这将完美地工作(这也是 Ben P 的答案所要求的(。

这是实现它的一种方法:

public void showThings(ArrayList<Thing> things) {
String json = new Gson().toJson(things);
Intent intent = new Intent(this, ThingActivity.class);
intent.putExtra(THINGS, json);
startActivity(intent);
}

然后你可以像这样得到数组列表:

String json = intent.getStringExtra(THINGS);
TypeToken<ArrayList<Things>> token = new TypeToken<ArrayList<Things>>() {};
ArrayList<Things> things = new Gson().fromJson(json, token.getType());

活动一:

val intent = Intent(this, SecondActivity::class.java)
val arrayGuide = ArrayList<Guide>()
intent.putParcelableArrayListExtra("arrayInfo",arrayGuide)
startActivity(intent)

活动二:

if(intent != null){
val arrayList = 
this.intent.getParcelableArrayListExtra<Guide>("arrayInfo")
}

相关内容

最新更新