代码之家  ›  专栏  ›  技术社区  ›  ray

kotlinandroid:如何通过intent传递可序列化对象的ArrayList而没有未检查的cast警告?

  •  1
  • ray  · 技术社区  · 7 年前

    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 似乎不像我在别处看到的那样管用

    2 回复  |  直到 7 年前
        1
  •  3
  •   Ben P.    7 年前

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

    虽然我同意你的看法,压制警告并不理想,但在这种情况下,我认为这是好的。

    这个 最好的 Parcelable Thing . 这样,当你想通过 通过意图,你可以写:

    intent.putParcelableArrayListExtra(THINGS, things)
    

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

    这两个都不会引起编译器警告。

        2
  •  2
  •   TheWanderer    7 年前

    你可以用 Gson .

    假设 Things

    下面是一种实现方法:

    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());
    
        3
  •  0
  •   Shivam Singh deepMerge    5 年前

    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")
    }