ProtectedVoid
ProtectedVoid

Reputation: 1315

Best way to create a data file in Android

What is the best way to create a data file in Android for saving data like usernames, configuration, and other variables accessible only by the Application?

Is there an official way to do this?

Upvotes: -1

Views: 293

Answers (1)

Nilton Vasques
Nilton Vasques

Reputation: 550

Android has some ways for save data.

Configurations are usually handled by Android Preferences. Where you can save your settings, doing something like this:

SharedPreferences settings = getSharedPreferences("APP_PREFS", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", true);
editor.commit();

For recover data, just do something like this:

// Restore preferences
SharedPreferences settings = getSharedPreferences("APP_PREFS", Context.MODE_PRIVATE);
boolean silent = settings.getBoolean("silentMode", false);

If you want to save more advanced type of data(make relationships between data, index, validations, avoid repeating), is better to use a database for it, and android provides an api to handle this using sqlite databases through SQLiteOpenHelper class.

More detailed example about android database you can find in this stackoverflow question: Android SQLite Example

Upvotes: 3

Related Questions