gpt4 book ai didi

java - 将项目添加到已在 Activity 之间传递的 ArrayList

转载 作者:行者123 更新时间:2023-11-29 05:20:26 24 4
gpt4 key购买 nike

我已经在 StackOverflow 和互联网上四处查看并尝试了一些东西,但所有这些都给了我同样的普遍问题。

我有一个 ArrayList,我在一个 Activity 中创建它,然后通过(另一个 Activity 或另外 2 个 Activity ,具体取决于用户的选择)发送它,并在每个 Activity (包括创建数组列表的 Activity )中让用户选择一个一组中的单个按钮。选择按钮后,我有一个监听器创建一个简单的字符串,然后将该字符串添加到 ArrayList,或者至少这是我想要它做的。

  1. 我已经尝试使用Serialized 类将同一个列表传递给它需要经历的所有 Activity
  2. 我尝试在每个类中创建一个新的 ArrayList,复制上一类通过 intent.putExtra() 发送然后接收的那个,这样它就可以被复制到一个新的数组列表中做同样的事情,直到它到达最终的 Activity 。
  3. 我试图理解 Parcleable 的实现,但它对我来说似乎太多了(我现在不擅长这个)。

每当我尝试使用 ArrayList 的 .add() 方法(或 .addAll() 第二次尝试完成此操作。

如果您必须向初学者提供任何建议和解释,我们将不胜感激!如果需要我可以放代码!!

最佳答案

首先,您应该使用Parcelable,在这种情况下效率更高。查看此链接以了解“为什么”:
https://medium.com/@theblackcat102/passing-object-between-activity-using-gson-7dfa11d74e06

其次,我会这样做:

public class ActivityOne extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
Intent intent = new Intent(this, ActivityTwo.class);
ArrayList<Person> strings = new ArrayList<Person>(Arrays.asList(new Person("Bob"),new Person("Dude")));
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(ActivityTwo.PARCELABLE_KEY,strings);
intent.putExtras(bundle);
startActivity(intent);
}
}


public class ActivityTwo extends Activity {
public static final String PARCELABLE_KEY = "array_key";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
if (getIntent() != null) {
ArrayList<Person> persons = getIntent().getParcelableArrayListExtra(PARCELABLE_KEY);
Log.d("test", persons.toString());
}
}
}

public class Person implements Parcelable {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Person() {
}

public Person(String name) {
this.name = name;
}


@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
}

public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
public Person createFromParcel(Parcel source) {
return new Person(source);
}

public Person[] newArray(int size) {
return new Person[size];
}
};

private Person(Parcel in) {
this.name = in.readString();
}
}

另外,不要害怕 Parcelables!作为一名优秀的开发人员,你应该偷懒,然后使用 Parcelable 生成器,例如:
http://www.parcelabler.com/

只需复制您的 POJO 类并生成(Android Studio 插件也存在)。

最后,不要忘记您不能在 2 个 Activity 之间传递无限数据。您还可以考虑将数据放入数据库。

关于java - 将项目添加到已在 Activity 之间传递的 ArrayList<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25002788/

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