2017-06-12 107 views
0

我正在製作一個應用程序,在其中設置了我的學校平衡設置,並且可以按專用按鈕根據購買的內容取走一定的金額。我在平衡方面遇到麻煩。我有辦法將它更新爲我想要的,但是在終止應用程序之後,我希望它在TextView中保持不變。到目前爲止,我能夠通過視頻將它保存到一個文件中,或者至少我希望是我。如何在打開應用程序時閱讀文本文件?

我怎麼能打開應用程序讀取文本文件,並設置TextView等於文件中的內容?

submitBtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      String submitAmount = amountEnter.getText().toString(); 
      balance.setText(submitAmount); 

      String myBalance = balance.getText().toString(); 

      try { 
       FileOutputStream fou = openFileOutput("balance.txt", 
MODE_WORLD_READABLE); 
       OutputStreamWriter osw = new OutputStreamWriter(fou); 
       try { 

        osw.write(myBalance); 
        osw.flush(); 
        osw.close(); 

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

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

     } 
    }); 
+1

得到它你可以使用'SharedPreference'來存儲您的數據。這裏是官方的Android文檔:[SharedPreference](https://developer.android.com/training/basics/data-storage/shared-preferences.html) – Pulak

+0

你的文件位於哪裏? SD卡或內存? –

+0

將文件保存到文件中可能很危險,因爲文件可能被移動或刪除(或更糟糕)。考慮使用SharedPreferences – Thecave3

回答

1

您可以將其保存在SharedPrefs 將其更改爲

submitBtn.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     String submitAmount = amountEnter.getText().toString(); 
     balance.setText(submitAmount); 
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()). 
edit().putString("balance", submitAmount).commit(); 

    } 
}); 

,您可以通過

String balance=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) 
.getString("balance","nothing_there"); 
+0

這應該是最正確的答案 – Thecave3

1

看到您的代碼,我假設您知道如何在android中讀取/寫入文件。如果沒有,那麼從這裏看。 https://stackoverflow.com/questions/12421814/how-can-i-read-a-text-file-in-android/您可以嘗試下面的代碼。 readfile方法來自上層鏈接。您只需從該活動的onCreate方法的文件中讀取特定的行/字符串即可。獲取所需TextView的引用,然後將文本設置爲TextView,如下所示。我希望它能幫助你

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.your_layout); 
     String texts = readfile(); 
     TextView textView = findViewById(R.id.text_view); 
     textView.setText(text); 


} 

private String readfile() { 
    File sdcard = Environment.getExternalStorageDirectory(); 
    File file = new File(sdcard, "file.txt"); 
    StringBuilder text = new StringBuilder(); 

    try { 
     BufferedReader br = new BufferedReader(new FileReader(file)); 
     String line; 

     while ((line = br.readLine()) != null) { 
      text.append(line); 
      text.append('\n'); 
     } 
     br.close(); 
    } catch (IOException e) { 
     //You'll need to add proper error handling here 
    } 

    return text.toString(); 
}