我的Arraylist只存储一个对象。每次输入新对象时,它都会覆盖当前对象。
通话方式:
public void saveBookingInfo(View view) {
EditText applicantNameText = (EditText) findViewById(R.id.applicantNameTextField);
EditText itemToBurnText = (EditText) findViewById(R.id.itemToBurnTextField);
String appName = applicantNameText.getText().toString();
String appItemToBurn = itemToBurnText.getText().toString();
if (appItemToBurn.isEmpty() || appName.isEmpty()) {
Toast.makeText(BookingScreen.this, "Please fill in all fields.", Toast.LENGTH_SHORT).show();
}
else {
sendApplication.storeApplication(appName, appItemToBurn);
this.finish();
}
}
ArrayList方法:
public void storeApplication(String name, String item){
ArrayList<Application> peopleAttending = new ArrayList<>(10);
peopleAttending.add(new Application(name, item));
}
答案 0 :(得分:7)
您将List<Application>
声明为方法的本地参数。将其作为类中的字段移动。
private List<Application> peopleAttending = new ArrayList<>();
public void storeApplication(String name, String item) {
peopleAttending.add(new Application(name, item));
}
答案 1 :(得分:1)
每次调用方法时,都会创建一个new
ArrayList。您应该只创建一次ArrayList
并传递对该方法的引用,或者将引用作为实例变量。
答案 2 :(得分:0)
您可以尝试更改对象sendApplication
的类的构造函数class SendApplication{
List<Application> peopleAttending = null;
public SendApplication(){
List<Application> peopleAttending = new ArrayList<Application>();
}
public void storeApplication(String name, String item) {
peopleAttending.add(new Application(name, item));
} //...... other methods follow
}