2012-08-02 42 views
0

的方法:安卓:ArrayList中傳遞給鑑於這種代碼不填充返回時

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

我希望this.SetupArray在loadSetups()以包含現有一個從readExternalStorageObjectFile()讀取配置信息,但它沒有。

如果我在readExternalStorageObjectFile()中放置了一個斷點,我發現obj在執行readObject()時確實包含了ArrayList信息。

但是,當它返回到loadSetups(),this.SetupArray不;它是空的。

我試圖將obj轉換爲ArrayList,但它是相同的結果。

回答

1

obj參數是一個指針。如果您使用obj = o.readObject()重新分配它,則不會修改引用的數據,您只需將指針重新分配給另一個內存位置即可。

一個解決方案是使該方法返回的對象:

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); 
} 
+0

謝謝你,這是我當時考慮的一個解決方案,但我想張貼此,看看是否有人能提供一個答案;你做到了。 – vedavis 2012-08-02 14:06:34