我是一个新的android开发人员。我正在开发一个示例应用程序。我想在对象列表中添加一些数据。
我的MainActivity.java类代码:
public class MainActivity extends Activity {
private PersonalInfo item;
private List<PersonalInfo> itemList = new ArrayList<PersonalInfo>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i < 5; i++) {
item.setFirstName("AA::" + i);
item.setLastName("BB::" + i);
item.setAddress("New City " + i);
item.setSex("Male");
itemList.add(item);
item = new PersonalInfo();
}
for(PersonalInfo p:itemList){
System.out.println("First Name::"+p.getFirstName());
System.out.println("Last Name::"+p.getLastName());
}
}
}
我的PersonalInfo.java类代码:
public class PersonalInfo {
private String firstName;
private String lastName;
private String address;
private String sex;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
当我运行它时,显示流动错误
感谢您的帮助。
答案 0 :(得分:4)
问题在这里:
for (int i = 0; i < 5; i++) {
item.setFirstName("AA::" + i); <-- error happened here because item is null
item.setLastName("BB::" + i);
item.setAddress("New City " + i);
item.setSex("Male");
itemList.add(item);
item = new PersonalInfo();
}
首先需要初始化item
,然后将数据设置为该值,因此您的代码必须是:
for (int i = 0; i < 5; i++) {
item = new PersonalInfo(); <-- I've moved this line
item.setFirstName("AA::" + i);
item.setLastName("BB::" + i);
item.setAddress("New City " + i);
item.setSex("Male");
itemList.add(item);
}
答案 1 :(得分:2)
改变你的for循环
for (int i = 0; i < 5; i++) {
item = new PersonalInfo(); // line1
item.setFirstName("AA::" + i);
item.setLastName("BB::" + i);
item.setAddress("New City " + i);
item.setSex("Male");
itemList.add(item);
}
for (PersonalInfo p : itemList) {
System.out.println("First Name::" + p.getFirstName());
System.out.println("Last Name::" + p.getLastName());
}
您的问题出在Line1
:您无法在不创建对象的情况下向对象插入值。因此,您必须先创建对象,然后初始化其属性。
答案 2 :(得分:1)
您只需要新建一个个人信息实例;
for (int i = 0; i < 5; i++) {
item = new PersonalInfo(); <-- I've moved this line
item.setFirstName("AA::" + i);
item.setLastName("BB::" + i);
item.setAddress("New City " + i);
item.setSex("Male");
itemList.add(item);
}