Java – how to add data in a list item in Android

I am a new Android Developer I am developing a sample application I want to add some data to the object list

My mainactivity Java class code:

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());
    }

}

}

My personalinfo Java class code:

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;
 }  

}

When I run it, then show the flow error

Thanks for your help.

Solution

Here's the problem:

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();
    }

You need to initialize the project first and then set the data to, so your code must be:

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);

        }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>