2014-02-09 175 views
0

我有一個數組列表,這是我創建的類的類型。我已經使用objectoutputstream將該數組列表寫入文件。現在我已經把它作爲一個對象讀回來了,但是我怎麼把它重新放回我的數組列表中?對象自定義類Arraylist

//Open external storage 
     File root = android.os.Environment.getExternalStorageDirectory(); 
     //Get directory path 
     File dir = new File(root.getAbsolutePath() + "/download"); 
     File file = new File(dir, "userAccounts.txt"); 

     try{ 
      FileInputStream fis = new FileInputStream(file); 
      ObjectInputStream ois = new ObjectInputStream(fis); 
      UserAccounts tempUser = (UserAccounts) ois.readObject(); 
      Global.getInstance().userArray.add(tempUser); 
      ois.close(); 
      Toast.makeText(getApplicationContext(), Global.getInstance().userArray.get(0).aUsername, Toast.LENGTH_LONG).show(); 

      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } catch (ClassNotFoundException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

package com.example.cg4project; 

import java.io.Serializable; 

public class UserAccounts implements Serializable{ 
    /** 
    * 
    */ 

    public int aID; 
    public String aUsername; 
    public String aFirstName; 
    public String aLastName; 
    public String aemail; 
v 

回答

0

如果它被保存爲一個ArrayList,你可以讀回這樣的:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); 
ArrayList<UserAccounts> myArray = (ArrayList<UserAccounts>) ois.readObject(); 

Global.getInstance().userArray.clear(); 
Global.getInstance().userArray.addAll(myArray); 
+0

如果我的ArrayList是一個全球性的ArrayList如何將我去有關存儲它在那 – xiimoss

+0

我更新了我的答案,以顯示如何將結果放入您的全局數組 – brwngrldev

+0

非常感謝! – xiimoss