2012-03-24 16 views
0

嗨在我的應用程序中,我保存了用戶輸入的字符串信息。然後序列化這些字符串以供稍後檢索。當我打開文件到他們保存的位置時,我總是隻收到輸入的最後一個字符串。你能看到我要去哪裏嗎?無法檢索所有保存的對象,並顯示在列表中

這是retrival代碼

protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.lightlist); 


    adapter = new ArrayAdapter<String>(LightList.this, android.R.layout.simple_list_item_1, lightNames); 

    refreshBut = (Button)findViewById(R.id.button1); 

      try { 
       File file = getCacheDir(); 
       fis = new FileInputStream(new File(file, LightSetup.FILENAME)); 

       ois = new ObjectInputStream(fis); 
          String a;   
          while((a = (String)ois.readObject()) != null){ 

         adapter.add(a); 

         setListAdapter(adapter); 
       } 

        ois.close(); 
      } catch (FileNotFoundException e) {e.printStackTrace();} catch (StreamCorruptedException e){e.printStackTrace(); 
      } catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} 
}//end onCreate 

這是序列化代碼

公共無效的onClick(查看爲arg0){

String stringData = data.getText().toString();  
     try { 

     File file = getCacheDir(); 
     fos = new FileOutputStream(new File(file,FILENAME)); 
     os = new ObjectOutputStream(fos); 
     os.writeObject(stringData); 
     fos.close(); 
     os.close(); 

    } catch (IOException e) {e.printStackTrace();} 

    Intent i = new Intent("com.Sonny.HCIProject.CreateConfirm"); 
    startActivity(i); 
    finish(); 

}//end onClick 
+0

發佈您的適配器 – Blackbelt 2012-03-24 16:23:41

回答

0

你正在做兩兩件事以錯誤的方式:

  1. 你不要做setListAdapter在一個循環中,儘管它可能不會對您造成任何傷害,您並不需要。
  2. onClick方法中的代碼不符合您的期望,它只是覆蓋您上次序列化的數據。您需要重新構建過去使用ObjectInputStream序列化的對象,然後將當前對象添加到對象圖(我認爲您需要一個List),然後可以安全地序列化文件中的所有對象而不覆蓋舊對象。

甚至可以序列喜歡的對象,我建議你在SQLite數據庫存儲在使用Java序列化,重建了一大堆不相關的對象,只是爲了保存另一個對象是矯枉過正的代替數據。用SQLite,你可以將一條記錄到數據庫中,然後你可以從數據庫的所有記錄中獲得SELECT,它速度很快,你的代碼會更簡潔。

+0

@Neevak感謝您的建議,我建立了SQLite,但獲取字符串並不容易。學習SQLite的權利很大。我認爲序列化每個字符串將是一條快速而又快捷的路線。 – codingNightmares 2012-03-24 18:34:10

+0

谷歌搜索「android sqlite」給出了很多資源。 Java序列化可以做你想做的事情,但這並不是最好的方式,正如我在答案中所解釋的那樣。 – neevek 2012-03-25 02:13:51

+0

順便說一句,如果這回答你的問題,請標記爲答案:) – neevek 2012-03-25 02:15:08

相關問題