【问题标题】:ArrayList<Object> to second activity using getSerializable problemArrayList<Object> 到使用 getSerializable 问题的第二个活动
【发布时间】:2019-11-15 00:33:17
【问题描述】:

在第一个活动中,我有一个必须传递给第二个活动的 ArrayList。

这是第一个活动:

public ArrayList<ItemContact> selectedContacts = new ArrayList<>(); //filled in the rest of the code

Intent intent = new Intent(this, SummaryActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("selectedContacts", selectedContacts);
intent.putExtra("selectedContacts", bundle);
startActivity(intent);

在第二个活动中:

ArrayList<ItemContact> selectedContacts = new ArrayList<>();

selectedContacts = (ArrayList<ItemContact>)getIntent().getExtras().getSerializable("selectedContacts") ;

问题是第二个活动中的 selectedContacts 始终为 null 我该如何解决?

编辑:ItemContact 已经实现了 Serializable 但仍然不起作用

【问题讨论】:

标签: android android-studio arraylist


【解决方案1】:

你的对象应该实现Serializable

class ItemContact implements Serializable {

  ......
} 

第一个活动

    public ArrayList<ItemContact> selectedContacts = new ArrayList<>(); 

    Intent intent = new Intent(this, SummaryActivity.class);
    Bundle bundle = new Bundle();

    bundle.putSerializable("selectedContacts", selectedContacts);
    intent.putExtras(bundle);
    startActivity(intent);

第二次活动

    ArrayList<ItemContact> selectedContacts = new ArrayList<>();

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();

    selectedContacts = (ArrayList<ItemContact>)bundle.getSerializable("selectedContacts");

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    使用 Parcelable 比可序列化更快,并通过活动传递多个对象数据。

    class ItemContact implements Parcelable {
    
     ......
    } 
    

    第一个活动

    public ArrayList<ItemContact> selectedContacts = new ArrayList<>(); 
    Intent intent = new Intent(this, SummaryActivity.class);
    intent.putParcelableArrayListExtra("selectedContacts", selectedContacts);
    startActivity(intent);
    

    第二次活动

    ArrayList<ItemContact> selectedContacts = new ArrayList<>();
    
    Intent intent = getIntent();
    
    selectedContacts = (ArrayList<ItemContact>)intent.getParcelableArrayListExtra("selectedContacts");
    

    如果您想要可序列化,请使用以下代码。使用 Serializable 实现类。

    第一个活动

    public ArrayList<ItemContact> selectedContacts = new ArrayList<>(); 
    Intent intent = new Intent(this, SummaryActivity.class);
    intent.putExtra("selectedContacts", selectedContacts);
    startActivity(intent);
    

    第二次活动

    ArrayList<ItemContact> selectedContacts = new ArrayList<>();
    
    Intent intent = getIntent();
    
    selectedContacts = (ArrayList<ItemContact>)intent.getSerializableExtra("selectedContacts");
    

    【讨论】:

      猜你喜欢
      • 2016-02-28
      • 1970-01-01
      • 2021-03-27
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多