1.调用Context对象的getSharedPreferences()方法
SharedPreferences preferences=getSharedPreferences("user",Context.MODE_PRIVATE);
2.四种模式
Context.MODE_PRIVATE:默认模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件.
Context.MODE_WORLD_READABLE:表示当前文件可以被其他应用读取.
Context.MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入.
3.将数据保存至SharedPreferences:
SharedPreferences preferences=getSharedPreferences("user",Context.MODE_PRIVATE);
Editor editor=preferences.edit();
String useerId="1001";
editor.putString("
useerId",
useerId);
editor.commit();
4.从SharedPreferences获取数据:
SharedPreferences preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
String name=preferences.getString("
useerId", "");
5.
从SharedPreferences删除数据:
SharedPreferences preferences=getSharedPreferences("user",Context.MODE_PRIVATE);
Editor editor=preferences.edit();
editor.clear();
editor.commit();
如果要做浏览搜索记录什么需要保存的,可以用下面的方法:
String roomListJson = sharedPref.getString(keyprefRoomList, null); if (roomListJson != null) { try { JSONArray jsonArray = new JSONArray(roomListJson); for (int i = 0; i < jsonArray.length(); i++) { roomList.add(jsonArray.get(i).toString()); } } catch (JSONException e) { Log.e("e", "Failed to load room list: " + e.toString()); } } adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, roomList); roomListview.setAdapter(adapter);