android-数据持久化
动态文件
String FILE_NAME = "tempfile.tmp"; try { //读 FileInputStream fis = openFileInput(FILE_NAME); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(isr); StringBuffer sb = new StringBuffer(); while (br.readLine() != null) { sb.append(br.readLine()+"\n"); } System.out.println(sb.toString()); //写 FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);//要让其它应用组件也能访问则用MODE_WORLD_WRITEABLE File file = new File(FILE_NAME); if (!file.exists()) { byte[] os = "write file".getBytes("UTF-8");//"这个例子测试文件写".getBytes("GB2312"); fos.write(os); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
静态文件资源
//这个id是在gen的R.java中生成id. 项目层次结构为res/raw里 InputStream is = getResources().openRawResource(R.raw.info); InputStreamReader isr; isr = new InputStreamReader(is, "UTF-8"); BufferedReader bfr = new BufferedReader(isr); String inString = ""; while ((inString = bfr.readLine()) != null) { Log.i(TAG, inString); }
首选项
int minimumMagnitude = 0; boolean autoUpdate = false; int updateFreq = 0; //读 Context context = getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); minimumMagnitude = Integer.parseInt(prefs.getString(Preferences.PREF_MIN_MAG, "0")); updateFreq = Integer.parseInt(prefs.getString(Preferences.PREF_UPDATE_FREQ, "0")); autoUpdate = prefs.getBoolean(Preferences.PREF_AUTO_UPDATE, false); //写 Context context = getApplicationContext(); prefs = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = prefs.edit(); editor.putBoolean(PREF_AUTO_UPDATE, autoUpdateChecked); editor.putInt(PREF_UPDATE_FREQ, updateIndex); editor.putInt(PREF_MIN_MAG, minMagIndex); editor.commit();
Preferences界面是继承PreferencesActivity,则只需要:
@res/xml/userpreferences.xml <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <CheckBoxPreference android:key="PREF_AUTO_UPDATE" android:title="Auto refresh" android:summary="Select to turn on automatic updating" android:defaultValue="true" /> <ListPreference android:key="PREF_UPDATE_FREQ" android:title="Refresh frequency" android:summary="Frequency at which to refresh earthquake list" android:entries="@array/update_freq_options" android:entryValues="@array/update_freq_values" android:dialogTitle="Refresh frequency" android:defaultValue="60" /> <ListPreference android:key="PREF_MIN_MAG" android:title="Minimum magnitude" android:summary="Select the minimum magnitude earthquake to report" android:entries="@array/magnitude_options" android:entryValues="@array/magnitude" android:dialogTitle="Magnitude" android:defaultValue="3" /> </PreferenceScreen> @PreferencesActivity public void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.userpreferences); }
否则,需要在Preferences中手动设置控件的状态值,包括ok和cancel键所执行的动作回调。
监听preference的改变
@Activity public void onCreate(Bundle icicle) { Context context = getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.registerOnSharedPreferenceChangeListener(this); } public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { }
从activity的preference中读写
private ListView myListView; private EditText myEditText; private static final String TEXT_ENTRY_KEY = "TEXT_ENTRY_KEY"; private static final String ADDING_ITEM_KEY = "ADDING_ITEM_KEY"; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Inflate your view setContentView(R.layout.main); // Get references to UI widgets myListView = (ListView)findViewById(R.id.myListView); myEditText = (EditText)findViewById(R.id.myEditText); restoreUIState(); } private void restoreUIState() { // Get the activity preferences object. SharedPreferences settings = getPreferences(0); // Read the UI state values, specifying default values. String text = settings.getString(TEXT_ENTRY_KEY, ""); Boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false); // Restore the UI to the previous state. if (adding) { addNewItem(); myEditText.setText(text); } } @Override protected void onPause() { super.onPause(); // Get the activity preferences object. SharedPreferences uiState = getPreferences(0); // Get the preferences editor. SharedPreferences.Editor editor = uiState.edit(); // Add the UI state preference values. editor.putString(TEXT_ENTRY_KEY, myEditText.getText().toString()); editor.putBoolean(ADDING_ITEM_KEY, addingNew); // Commit the preferences. editor.commit(); }
状态
private static final String SELECTED_INDEX_KEY = "SELECTED_INDEX_KEY"; @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(SELECTED_INDEX_KEY, myListView.getSelectedItemPosition()); super.onSaveInstanceState(outState); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { int pos = -1; if (savedInstanceState != null) if (savedInstanceState.containsKey(SELECTED_INDEX_KEY)) pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1); myListView.setSelection(pos); }