1

This is related to Array of objects in a class. I originally added it on to that question but because that question was answered I wasn't getting responses.

So I have 2 classes. One containing a list of the other class. And I am adding data into the class that I have pulled out of the database. However when I go to pull the data back out of the List, values are all the same. They are the values of the last element in the list.

I have tried creating the object anew in each loop but it still seems to be causing a problem. I don't see what I am doing wrong here.

public class xmldata {
    String Barcode;
    String First;
    String Last;
    String Phone;
    String Email;

    String md5sum;

    String zipfile;

    List<PictureData> pics = new ArrayList<PictureData>();

...

public class PictureData {

    static String filename;
    static String directory;

...

xmldata data = new xmldata();

ResultSet pictures=db.query("select * from pictures where barcode=?",barcode);



while (pictures.next()) {
    PictureData pictemp= new PictureData();
    pictemp.setdirectory(pictures.getString("path"));
    pictemp.setfilename(pictures.getString("filename"));
    data.pics.add(pictemp);     
} 

...

for (int j=0; j<data.pics.size();++j) {

    String path;
    PictureData pictemp2= new PictureData();

    pictemp2=(PictureData) data.pics.get(j);
    path=pictemp2.getdirectory()+pictemp2.getfilename();

    System.out.println(path);

    zip.addfile(path);

}
8
  • Have you breaked after your while to see the content in data.pics ? Commented Apr 28, 2013 at 2:44
  • It doesn't actually tell me what's in there. It just lists pics>elementData>[0]PictureData(id=43) and pics>elementData>[1]PictureData(id=45) Commented Apr 28, 2013 at 2:50
  • Where is your PictureData? Commented Apr 28, 2013 at 2:51
  • @JermaineXu: check the previous post he has mentioned. Its there. Commented Apr 28, 2013 at 2:52
  • Sorry thought it was in what I copied. Commented Apr 28, 2013 at 2:52

1 Answer 1

5

Problem is here:

public class PictureData {

    static String filename;
    static String directory;

}

Why have you made filename and directory static? it can contain only one value. Make them non static and it will work.

Sign up to request clarification or add additional context in comments.

3 Comments

So eventhough, I had multiple instances of the class, it could only hold one value because it was static and thus the same against all instances?
@Codeguy007: Yup , static is at class level not instance level.
I have the same problem and I also havent declared them static. not sure why

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.