《老罗Android》学习之数据存储

1.  5种方式
在实际开发中,Android提供了5种方式存储数据
  1. 文件存储数据
  2. 使用SharedPreferences存储数据
  3. SQLite数据库存储数据
  4. 使用ContentProvider存储数据
  5. 网络存储数据
2. File:读写SD卡上的文件
1.为了能读写SD卡上的数据,必须在应用程序的清单文件中添加读写SD卡的权限

<!-- 允许用户创建和删除sdcard卡上的内容 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
<!-- 允许用户往sdcard卡上写入的内容 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
再加入单元测试 <instrumentation>
<instrumentation  android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.example.android_sdcard" >
再在<Application>标签中加入库的支持
<uses-library android:name="android.test.runner"/>
2. 实现写入和读取sdcard
</pre><pre name="code" class="java">public class FileService {
private Context context;
public FileService(Context context) {
	this.context = context;
}
public FileService() {
}
public String getFileFromSdcard(String fileName) {
	FileInputStream inputStream = null;
	// 缓存的流,和磁盘无关,不需要关闭
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	File file = new File(Environment.getExternalStorageDirectory(),fileName);
	if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
		try {
			inputStream = new FileInputStream(file);
			int len = 0;
			byte[] data = new byte[1024];
			while ((len = inputStream.read(data)) != -1) {
				outputStream.write(data, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	return new String(outputStream.toByteArray());
}
/**@param fileName         文件的名称
 * @param content          文件的内容 */
public boolean saveContentToSdcard(String fileName, String content) {
	boolean flag = false;
	FileOutputStream fileOutputStream = null;
	// 获得sdcard卡所在的路径
	File file = new File(Environment.getExternalStorageDirectory(),fileName);
	// 判断sdcard卡是否可用
	if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
		try {
			fileOutputStream = new FileOutputStream(file);
			fileOutputStream.write(content.getBytes());
			flag = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	return flag;
	}
}
如果要在sdcard目录新建一个文件夹,可以用如下代码:
//在SD卡上创建一个文件夹
public String createSDCardDir(){
// 创建一个文件夹对象,赋值为外部存储器的目录
File sdcardDir =Environment.getExternalStorageDirectory();
//要创建文件夹的路径
String path=sdcardDir.getPath()+"/cardImages";
File path1 = new File(path);
if (!path1.exists()) {
       //若不存在,创建目录,可以在应用启动的时候创建
      path1.mkdirs();
    }else{return ""}
  return path;
}
3. 写一个测试类
public class MyTest extends AndroidTestCase {
	private final String TAG = "MyTest";
	public MyTest() {
	}
	public void saveFile() {
		Context context = getContext();
		FileService fileService = new FileService(context);
		boolean flag = fileService.saveContentToSdcard("hello.txt", "你好");
		Log.i(TAG, "-->>" + flag);
	}
	public void readFile() {
		Context context = getContext();
		FileService fileService = new FileService(context);
		String msgString = fileService.getFileFromSdcard("hello.txt");
		Log.i(TAG, "--->>" + msgString);
	}
}
在要运行的方法上单击右键,ran as---->Android JUnit  test.
2. SharedPreferences
SharedPreferences在存储数据类型的时候,不仅仅能存储简单数据类型,也可以存放复杂的数据类型。
1. 要用到测试类,同上一样,要加入TestRunner  <instrumentation>和库 <uses-library android:name="android.test.runner"/>
2.实现读写SharedPreferences
public class MyPreference {
	private Context context;
	public MyPreference(Context context) {
		this.context = context;
	}
	public boolean saveMessage(String name, String pswd) {
		boolean flag = false;
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				"userinfo", Context.MODE_PRIVATE);
		// 对数据进行编辑
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString("name", name);
		editor.putString("pswd", pswd);
		flag = editor.commit();// 将数据持久化到存储介质中
		return flag;
	}
	public Map<String, Object> getMessage() {
		Map<String, Object> map = new HashMap<String, Object>();
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				"userinfo", Context.MODE_PRIVATE);
		String name = sharedPreferences.getString("name", "");
		String pswd = sharedPreferences.getString("pswd", "");
		map.put("name", name);
		map.put("pswd", pswd);
		return map;
	}
}
3. 写一个测试类
public class MyTest extends AndroidTestCase {
	private String TAG = "MtTest";
	public MyTest() {
	}
	public void save() {
		Context context = getContext();
		MyPreference mySharedpreference = new MyPreference(context);
		boolean flag = mySharedpreference.saveMessage("admin", "123");
		Log.i(TAG, "-->>" + flag);
	}
	public void find() {
		Context context = getContext();
		MyPreference sharedpreference = new MyPreference(context);
		Map<String, Object> map = sharedpreference.getMessage();
		Log.i(TAG, "--->>" + map.toString());
	}
}

实际上android将SharedPreferences的参数保存到手机内存私有的目录中,保存的路径是在/data/data/packagename/shared_prefs目录中,保存的格式都是“文件名.xml”结束的。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值