gpt4 book ai didi

java - 将 ArrayList 传递给新 Activity

转载 作者:行者123 更新时间:2023-12-02 12:36:14 25 4
gpt4 key购买 nike

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

但是我无法将对象传输到新 Activity ,我在新 Activity 上得到空值。

我读到我需要对 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 实现 Parcelable 接口(interface)来传输此 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")

来获取此数组

希望这有帮助。

关于java - 将 ArrayList<Person> 传递给新 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45120086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com