简体   繁体   English

Android写文件什么都不做

[英]Android write file does nothing

I have a program where I want to save what the user entered for use in later runs. 我有一个程序要保存用户输入的内容,以供以后运行。 I am currently trying to save it to a text file. 我目前正在尝试将其保存到文本文件。 I can run the program fine and everything seems to work, but at the end I check the file and its untouched. 我可以很好地运行该程序,并且一切似乎都可以正常运行,但是最后我检查了文件及其未更改的内容。 Here is the code: 这是代码:

public void onClick(View v) 
    {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.activity_tax_popup, (ViewGroup) findViewById(R.id.taxWindow), false);

        String filename = "tax.txt";
        boolean isEnabled = layout.findViewById(R.id.taxBox).isEnabled();
        String enable = String.valueOf(isEnabled);
        String taxPercent = layout.findViewById(R.id.enterTax).toString();
        FileOutputStream fos;

        try 
        {
            fos = openFileOutput(filename, Context.MODE_PRIVATE);
            fos.write(enable.getBytes());
            fos.write(taxPercent.getBytes());
            fos.close();
        } 
        catch (Exception e) 
            {e.printStackTrace();}

        pw.dismiss();       
    }

How can I change it to write to a file? 如何更改它以写入文件? Also if anyone knows a better way to save data between runs I'm open to suggestions. 另外,如果有人知道在两次运行之间保存数据的更好方法,那么我也会提出建议。

There's a beautiful little thing called shared preferences for this exact thing :) 对于这个确切的东西,有一个美丽的小东西叫做共享首选项:)

Here is an example from the Android Developer Guide : 这是《 Android开发人员指南》中的示例:

public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";

@Override
protected void onCreate(Bundle state){
   super.onCreate(state);
   . . .

   // Restore preferences
   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
   boolean silent = settings.getBoolean("silentMode", false);
   setSilent(silent);
}

@Override
protected void onStop(){
   super.onStop();

  // We need an Editor object to make preference changes.
  // All objects are from android.context.Context
  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putBoolean("silentMode", mSilentMode);

  // Commit the edits!
  editor.commit();
}
}

You can (and probably will), of course, do more than just putBoolean - I find myself using putString("HEY THERE"); 当然,您可以(而且可能会)做更多的事情,而不仅仅是putBoolean-我发现自己使用putString(“ HEY THERE”); much more often. 经常。

I hope this helps. 我希望这有帮助。 Good luck :) 祝好运 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM