【问题标题】:Passing ArrayList<Person> to new activity将 ArrayList<Person> 传递给新活动
【发布时间】:2017-07-16 15:13:54
【问题描述】:

我想将 ArrayList 传递给新活动,在新活动中我将使用 ArrayAdapter 加载列表。

但我无法将对象转移到新活动中,我在新活动上得到了空值。

我读到我需要对 Person 类实现序列化... 这是唯一的方法吗?

这是我的代码:

AsyncTask onPostExecute 我正在获取数组。

@Override
    protected void onPostExecute(ArrayList<Person> personArrayList){

        Intent intent = new Intent(activity, ResultsActivity.class);
        intent.putExtra("personArrayList",personArrayList);
        activity.startActivity(intent);

    }

使用 putExtra 发送。

这里是假设接收数组的 Activity。

public class ResultsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_results);
        Intent intent = getIntent();
        ArrayList<Person> personArrayList = (ArrayList<Person>) intent.getSerializableExtra("personArrayList");

        PeopleAdapter adapter = new PeopleAdapter(this, personArrayList);

        // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
        // There should be a {@link ListView} with the view ID called list, which is declared in the
        // activity_results.xml layout file.

        ListView listView = (ListView) findViewById(R.id.list);


        // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
        // {@link ListView} will display list items for each {@link Person} in the list.
        listView.setAdapter(adapter);
    }
}

所以在接收端 ArrayList 是空的。想法?

【问题讨论】:

  • 是的,你需要在 Person 类上实现 Serializable
  • 在ResultsActivity中获取intent时尝试这样。 personArrayList = getIntent().getStringArrayListExtra("personArrayList");

标签: java android android-intent arraylist


【解决方案1】:

您可以通过使您的类 Person 实现 Parcelable 接口来传输此 ArrayList。完成后,您需要做的就是编写:

@Override
protected void onPostExecute(ArrayList<Person> personArrayList){

    Intent intent = new Intent(activity, ResultsActivity.class);
    intent.putParcelableArrayListExtra("personArrayList",personArrayList);
    activity.startActivity(intent);

}

在您的 ResultsActivity 类中,您可以通过编写 intent.getParcelableArrayListExtra("personArrayList") 来获取此数组

希望这会有所帮助。

【讨论】:

【解决方案2】:

是的,您需要在 Person 类上实现 Serializable

ArrayList 是可序列化的,但如果它的内容不是,那么将无法对其进行序列化/反序列化。

只需将implements Serializable 添加到您的班级,您就可以开始了。

【讨论】:

【解决方案3】:

对于这种类型的场景,您可以使用全局变量来设置和获取值。但请注意,这不是完全可靠的解决方案。

用于设置值

((ApplicationClassName)getApplicationContext()).setDataArrayList(personArrayList);

用于检索值

ArrayList<Person> personArrayList =((ApplicationClassName)getApplicationContext()).getDataArrayList();

【讨论】:

    猜你喜欢
    • 2016-05-13
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 2014-03-07
    相关资源
    最近更新 更多