Reputation: 1653
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.
Upvotes: 0
Views: 81
Reputation: 8338
There's a beautiful little thing called shared preferences for this exact thing :)
Here is an example from the Android Developer Guide:
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"); much more often.
I hope this helps. Good luck :)
Upvotes: 1