初学_Android4高级编程-8 share preference&文件&状态保存
※使用share preference保存数据
SharedPreferences sharedPreferences = getSharedPreferences("setting", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("int",1);
editor.putString("String","str");
editor.putBoolean("boolean",true);
//apply()异步保存,commit()同步保存
editor.commit();
sharedPreferences.getString("String","def");
sharedPreferences.getBoolean("boolean",false);
使用preferenceScreen
在xml文件夹中新建xml文件
<CheckBoxPreference
android:key="checkbox"
android:summary="男 ,女"
android:title="性别" />
<RingtonePreference
android:key="ringtone"
android:showDefault="true"
android:showSilent="true"
android:summary="Pick a tone, any tone"
android:title="Ringtone Preference" />
<ListPreference
android:entries="@array/my_array"
android:entryValues="@array/my_array"
android:key="list"
android:summary="select a list"
android:title="Type" />
<EditTextPreference
android:dialogTitle="nihao"
android:key="edit"
android:title="姓名" />
·使用saveInstanceState保存Activity,Fragment状态
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
if(savedInstanceState != null){
userSelection = savedInstanceState.getInt(USER_SELECTION)
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(USER_SELECTION,userSelection);
super.onSaveInstanceState(outState);
}
※在文件中保存数据
·将文件保存到对应包名的目录下
String filename = "name.txt";
String str = "哈哈";
FileOutputStream fileOutputStream;
try {
fileOutputStream = openFileOutput(filename, Context.MODE_PRIVATE);
fileOutputStream.write(str.getBytes());
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
String ans = ReadTxtFile(this.getFilesDir() + "/" + filename);
Toast.makeText(this, ans.trim(), Toast.LENGTH_SHORT).show();
·读取对应目录下的文件输出字符内容
public String ReadTxtFile(String strFilePath) {
String path = strFilePath;
String content = ""; //文件内容字符串
//打开文件
File file = new File(path);
//如果path是传递过来的参数,可以做一个非目录的判断
if (file.isDirectory()) {
Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
} else {
try {
InputStream instream = new FileInputStream(file);
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
//分行读取
while ((line = buffreader.readLine()) != null) {
content += line + "\n";
}
instream.close();
}
} catch (Exception e) {
Toast.makeText(this, "失败", Toast.LENGTH_SHORT).show();
}
}
return content;
}
·通过Environment.getExternalStorageDirectory()获取sd卡目录,保存文件到sd卡中,需要sd卡权限
File sdCardDir = Environment.getExternalStorageDirectory();
File file = new File(sdCardDir, filename);
浙公网安备 33010602011771号