Android Saving Data

来源:互联网 发布:数据挖掘软件容易使用 编辑:程序博客网 时间:2024/06/07 13:01

Android Saving Data

There are three options to save data in android:

  • Saving key-value pairs of simple data types in a shared preferences file
  • Saving arbitrary files in Android’s file system
  • Saving structured data by using SQLite database

SharedPreferences

Android framework provides the SharedPreferences APIs to storage small collection of key-values, such as login name and login pwd. Each SharedPreference file will be saved as a .xml file in the dir of “/data/data/your_app_pkg_dir”.

Access or create:

You can create a new shared preference file or access an exiting one by the sample code below(For
example, the following code is executed in a Fragment):

Context context = getActivity();SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREF_KEY, Context.MODE_PRIVATE);

Alternativly, if you need just one shared preference file for your activity, you can just use:

SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);

Write

To write to a shared preference file, create a Sharedpreferences.Editor by calling editor() on your sharedPreferences, and then call the methods such as putInt() or putString(). At last, call commit() to save the changes. For example:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPref.edit();editor.putString("name", "sen.tian");editor.putInt("age", 26);editor.commit();

Read

To retrieve values from a shared preferences file, call the methods such as getInt() or getString(), providing the key for the value you want, and optionally a default key to return if the key isn’t present. For example:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);long highScore = sharedPref.getInt("age", 0);

Files

Internal Storage

  • Always available. No need to add permission.
  • Files saved here are accessible by only your app.
  • When app is uninstalled, app’s files will all be removed.

External Storage

  • Not Always available. Need to add permission of android.permission.WRITE_EXTERNAL_STORAGE in AndroidMenifest.xml.
  • Files saved here are world-readable, so the data will be not safe here.
  • The app’s files will be removed only if you save them in the dir from getExternalFileDir() when app is uninstalled.