2012-07-23 54 views
0

我試圖保存和加載字符串到/從內部存儲的方式,允許用戶退出應用程序,甚至關閉手機,但仍然訪問此字符串每當該應用程序被使用。從Android的內部存儲加載文件

當我退出應用程序並重新輸入時,它不會加載之前存儲的字符串。我需要它來加載以前的字符串,即使我重新啓動手機。以下是我迄今爲止:

EditText sharedData; 
TextView dataResults; 
FileOutputStream fos; 
String FILENAME = "InternalString"; 

protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.sharedpreferences); 
    setupVariables(); 
} 

private void setupVariables() { 
    // TODO Auto-generated method stub 
    sharedData = (EditText) findViewById(R.id.editText_SharedPrefs); 
    dataResults = (TextView) findViewById(R.id.textView_LoadSharedPrefs); 
    Button save = (Button) findViewById(R.id.button_save); 
    Button load = (Button) findViewById(R.id.button_load); 
    save.setOnClickListener(this); 
    load.setOnClickListener(this); 
    try { 
     fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
     fos.close(); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

@Override 
public void onClick(View v) { 
    // TODO Auto-generated method stub 
    switch (v.getId()) { 
    case R.id.button_save: 
     String data = sharedData.getText().toString(); 
     try { 
      fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
      fos.write(data.getBytes()); 
      fos.close(); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     break; 
    case R.id.button_load: 
     String collected = null; 
     FileInputStream fis = null; 
     try { 
      fis = openFileInput(FILENAME); 
      byte[] dataArray = new byte[fis.available()]; 
      while(fis.read(dataArray) != -1){ 
       collected = new String(dataArray); 
      } 
      dataResults.setText(collected); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } finally { 
      try { 
       fis.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
     break; 
    } 
} 
+0

歡迎堆棧溢出!我們通常喜歡這個網站上的問題是關於特定的編程問題。你的問題到底是什麼? – gobernador 2012-07-23 00:22:01

+0

哦,親愛的 - 我忘了實際指定發生了什麼,致歉!當我退出應用程序並重新輸入時,它不會加載我以前存儲的數據。 – 2012-07-23 00:41:55

回答

0

取決於你使用你應該使用SharedPreferences而不是寫文件...除非它是一個大量數據的什麼樣的「弦」。

getSharedPreferences(getPackageName() , MODE_PRIVATE).edit().putString("myString").commit(); 

這將持續通過手機powercycles。如果你卸載應用程序,它會迷路(這可能是一件好事)。

下面是所有的各種數據保存可能向你敞開了Android文檔...

Saving Stuff On Android

+0

這個工程!非常感謝:) – 2012-07-23 17:37:14

+0

不客氣! – 2012-07-23 19:57:13

相關問題