SharedPreference概念、作用
SharedPreference保存的数据主要是类似于配置信息格式的数据,因此它保存数据主要是简单类型的key-value对
SharedPreference接口主要负责读取应用程序的Preferences数据,提供了如下常用方法
boolean contains(String key)
|
判断SharedPreferences是否包含特定key的数据
|
abstract Map<String, ?> getAll()
|
获取SharedPreference数据里的全部key-value对
|
boolean getXxx(String key, xxx defValue)
|
获取指定key对应的value,如果该key不存在,返回默认值defValue。xxx可以是boolean、Float、int、long、String等
|
SharedPreferences接口本身并没有提供写入数据的能力,而是通过SharedPreferences的内部接口,SharedPreferences调用edit()方法即可获取它所对应的Editor对象,Editor提供了如下方法来向SharedPreferences写入数据
SharedPreferences.Editor clear()
|
清空所有数据
|
SharedPreferences.Editor putXxx(String key, xxx value)
|
存入指定key对应的数据。xxx可以是boolean、float、int、long、String等基本类型
|
SharedPreferences.Editor remove(String key)
| 删除指定key对应的数据项 |
boolean commit()
|
当Editor编辑完成后,调用该方法提交修改
|
SharedPreferences本身是一个接口,程序无法直接创建SharedPreferences实例,只能通过Context提供的getSharedPreferences(String name, int mode)方法来获取SharedPreferences实例,该方法的第二个参数支持如下几个值:
Context.MODE_PRIVATE
|
指定该SharedPreferences数据只能被本应用程序读写
|
Context.MODE_WORLD_READABLE
|
能被其他程序读,但不能写
|
Context.MODE_WORLD_WRITEABLE
|
能被其他程序读写
|
实例代码:
public
class
SharedPreferencesTest
extends
ActionBarActivity {
SharedPreferences preferences ;
SharedPreferences.Editor editor ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. main );
preferences = getSharedPreferences( "crazyit" ,MODE_WORLD_READABLE);
editor = preferences .edit();
Button read = (Button) findViewById(R.id. read );
Button write = (Button) findViewById(R.id. write );
read.setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View source)
{
String time = preferences .getString( "time" , null );
int randNum = preferences .getInt( "random" , 0);
String result = time == null ? "not write yet" : "write time:"
+time + "\nthe random number produced last time :" + randNum;
Toast.makeText(SharedPreferencesTest. this , result, 3000).show();
}
});
write.setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View source)
{
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy/mm/dd "
+ "hh:mm:ss" );
editor .putString( "time" , sdf.format( new Date()));
editor .putInt( "random" , ( int )(Math.random() * 100));
editor .commit();
}
});
}
SharedPreferences preferences ;
SharedPreferences.Editor editor ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. main );
preferences = getSharedPreferences( "crazyit" ,
editor = preferences .edit();
Button read = (Button) findViewById(R.id. read );
Button write = (Button) findViewById(R.id. write );
read.setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View source)
{
String time = preferences .getString( "time" , null );
int randNum = preferences .getInt( "random" , 0);
String result = time == null ? "not write yet" : "write time:"
+time + "\nthe random number produced last time :" + randNum;
Toast.makeText(SharedPreferencesTest. this , result, 3000).show();
}
});
write.setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View source)
{
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy/mm/dd "
+ "hh:mm:ss" );
editor .putString( "time" , sdf.format( new Date()));
editor .putInt( "random" , ( int )(Math.random() * 100));
editor .commit();
}
});
}
读写其他程序SharedPreferences
要读写某应用,该应用的读写权限应是提前授予的
读取SharedPreferences步骤如下:
- 需要创建其他程序对应的Context,例如 useCount = createPackageContext(“com.example.io”,Context.CONTEXT_IGNORE_SECURITY);
- 调用其他应用程序的Context的getSharedPreferences(String name, int mode)即可获取相应的SP
- 如需写入,调用SP的edit()方法获取相应Editor即可
File 存储
FileInputStream
FileOutputStream
openFileOutput和 openFileInput
Context提供了如下两个方法来打开本应用程序的数据文件夹里的文件I/O流
FileInputStream openFileInput(String name)
FileOutputStream openFileInput(String name, int mode)
第二个方法的第二个参数指定打开文件的模式,支持如下值:
MODE_PRIVATE
MODE_APPEND 以追加方式打开
MODE_WORLD_READABLE
MODE_WORLD_WRITEABLE
另外,Context还提供了如下几个方法来访问应用程序的数据文件夹
getDir(String name, int mode)
|
在应用程序的数据文件夹下获取或创建name对应的子目录
|
File getFilesDir()
|
获取该应用程序的数据文件夹的绝对路径
|
String[] fileList()
|
返回该应用程序的数据文件夹下的全部文件
|
deleteFile(String)
|
删除该应用程序的数据文件夹下的指定文件
|
示例程序
main.xml
<
LinearLayout
xmlns:android
=
"http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical" >
< EditText
android:id = "@+id/edit1"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:text = "hello_world" />
< Button
android:id = "@+id/write"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "write" />
< EditText
android:id = "@+id/edit2"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:editable = "false"
android:lines = "4"
android:text = "hello_world" />
< Button
android:id = "@+id/read"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "read" />
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical" >
< EditText
android:id = "@+id/edit1"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:text = "hello_world" />
< Button
android:id = "@+id/write"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "write" />
< EditText
android:id = "@+id/edit2"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:editable = "false"
android:lines = "4"
android:text = "hello_world" />
< Button
android:id = "@+id/read"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "read" />
</
LinearLayout
>
FileTest.java
public
class
FileTest
extends
ActionBarActivity {
final String FILE_NAME = "android_file_test.bin" ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. main );
System. out .println( new StringBuilder( "a" )
.append( "b" ).append( "c" ).toString());
Button read = (Button) findViewById(R.id. read );
Button write = (Button) findViewById(R.id. write );
final EditText edit1 = (EditText) findViewById(R.id. edit1 );
final EditText edit2 = (EditText) findViewById(R.id. edit2 );
write.setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
write(edit1.getText().toString());
edit1.setText( "" );
}
});
read.setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
edit2.setText(read());
}
});
}
private String read()
{
try {
FileInputStream fis = openFileInput( FILE_NAME );
byte [] buff = new byte [1024];
int hasRead = 0;
StringBuilder sb = new StringBuilder( "" );
while ((hasRead = fis.read(buff))>0)
{
sb.append( new String(buff, 0 ,hasRead));
}
fis.close();
return sb.toString();
} catch (Exception e){
e.printStackTrace();
}
return null ;
}
private void write(String content)
{
try {
FileOutputStream fos = openFileOutput( FILE_NAME , MODE_APPEND );
PrintStream ps = new PrintStream(fos);
ps.println(content);
ps.close();
} catch (Exception e){
e.printStackTrace();
}
}
final String FILE_NAME = "android_file_test.bin" ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. main );
System. out .println( new StringBuilder( "a" )
.append( "b" ).append( "c" ).toString());
Button read = (Button) findViewById(R.id. read );
Button write = (Button) findViewById(R.id. write );
final EditText edit1 = (EditText) findViewById(R.id. edit1 );
final EditText edit2 = (EditText) findViewById(R.id. edit2 );
write.setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
write(edit1.getText().toString());
edit1.setText( "" );
}
});
read.setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
edit2.setText(read());
}
});
}
private String read()
{
try {
FileInputStream fis = openFileInput( FILE_NAME );
byte [] buff = new byte [1024];
int hasRead = 0;
StringBuilder sb = new StringBuilder( "" );
while ((hasRead = fis.read(buff))>0)
{
sb.append( new String(buff, 0 ,hasRead));
}
fis.close();
return sb.toString();
} catch (Exception e){
e.printStackTrace();
}
return null ;
}
private void write(String content)
{
try {
FileOutputStream fos = openFileOutput( FILE_NAME , MODE_APPEND );
PrintStream ps = new PrintStream(fos);
ps.println(content);
ps.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
读写SD卡上的文件
读写SD卡步骤如下:
- 调用Environment的getExternalSrorageState()方法判断手机是否插入SD卡,并且判断是否有读写权限;
- 调用Environment的getExternalStorageDirectory()方法来获取外部存储器,也就是SD卡的目录
- 使用FileInputStream、FileOutputStream、FileReader或FileWriter读写sd里的文件