Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to data add in List<Object> items in android

Tags:

java

android

I am a new android developer.I am developing a sample application .I want to add some data in a 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 flowing error enter image description here

Thanks for your help.

like image 619
Sams Avatar asked Oct 30 '25 07:10

Sams


1 Answers

problem is here:

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 first initialize item then set data to that, 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);

        }
like image 183
Shayan Pourvatan Avatar answered Oct 31 '25 20:10

Shayan Pourvatan