vedavis
vedavis

Reputation: 968

android: ArrayList passed to a method not populated upon return

Given this code:

public class TestSetup extends Object implements Serializable {
   // ... some data and methods
}
ArrayList SetupArray = new ArrayList<TestSetup>();
// ----------------------------------------------
    public boolean readExternalStorageObjectFile(String filename, Object obj) {
    boolean isOk = true;
    try {
        File path = new File(sDirectoryPath + sTopDirectoryObj, filename);
        FileInputStream out = new FileInputStream(path);
        ObjectInputStream o = new ObjectInputStream(out);
        obj = o.readObject();
        o.close();
    }
    catch(Exception e) {
        Log.e("Exception","Exception occured in reading");
        isOk = false;
    }        
    return isOk;
}

// ----------------------------------------------
public void loadSetups() {
    this.SetupArray.clear();
    this.readExternalStorageObjectFile(SETUPS_FILENAME, this.SetupArray);
}

I would expect this.SetupArray in loadSetups() to contain existing array information that was read from readExternalStorageObjectFile(), but it doesn't.

If I put a breakpoint in readExternalStorageObjectFile(), I see that obj does contain the ArrayList information when readObject() is executed.

But when it returns back to loadSetups(), this.SetupArray does not; it is empty.

I've tried to cast obj as ArrayList, but it's the same result.

Upvotes: 0

Views: 81

Answers (1)

sdabet
sdabet

Reputation: 18670

The obj parameter is a pointer. If you reassign it with obj = o.readObject() you don't modify the referenced data, you just reassign the pointer to another memory location.

A solution would be to make the method return the object:

ArrayList SetupArray = new ArrayList<TestSetup>();

public Object readExternalStorageObjectFile(String filename) {
    try {
        File path = new File(sDirectoryPath + sTopDirectoryObj, filename);
        FileInputStream out = new FileInputStream(path);
        ObjectInputStream o = new ObjectInputStream(out);
        Object obj = o.readObject();
        o.close();
        return obj;
    }
    catch(Exception e) {
        Log.e("Exception","Exception occured in reading");
        return null;
    }        
}

public void loadSetups() {
    this.SetupArray = (ArrayList) this.readExternalStorageObjectFile(SETUPS_FILENAME);
}

Upvotes: 1

Related Questions