Android保存数据的方式有很多种:
1)SQLite:轻量级数据库存储数据;
2)File:以文件形式将数据保存到SD卡;
3)Shared Preferences:以键值对的形式保存数据;
4)Server:通过网络服务器数据库来保存数据;
5)Content Providers:数据共享,应用程序间的数据访问;
这里主要是通过文件的形式保存数据:
1、添加权限到manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <!-- 写入SD卡权限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- 在SD卡中创建和删除文件的权限 -->
2、保存数据到SD卡,现将传入的List<Map<String,Object>>类型数据转换成String类型数据,再将其保存到名为chatRecord的txt文件中。
//保存数据到SD卡文件 public boolean saveDataToSDcard(String fileName,List<HashMap<String,Object>> list){ boolean isAvailable = false; //SD是否可读 FileOutputStream fileOutputStream = null; //创建File对象 File file = new File(Environment.getExternalStorageDirectory(),fileName); //将list转成String类型 List<String> cache = new ArrayList<String>(); for (int i = 0; i < list.size(); i++) { // 取出当前的Map,转化为JSONObject JSONObject obj = new JSONObject(list.get(i)); // 转化为字符串并添加进新的List中 cache.add(obj.toString()); } // 可存储的字符串数据 String listStr = cache.toString(); //判断SD卡是否可读写 if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){ isAvailable = true; try { fileOutputStream = new FileOutputStream(file); fileOutputStream.write(listStr.getBytes()); if(fileOutputStream != null){ fileOutputStream.close(); } } catch (Exception e) { e.printStackTrace(); } } return isAvailable; }调用函数形式,chatList为要传递的List<Map<String,Object>>类型数据实例:
//保存聊天记录到txt boolean saveFileIsSuccess = saveDataToSDcard("chatRecord.txt", chatList);
//读取文件内容,并将String转成List<> public List<Map<String, Object>> getDataFromSDcard(String fileName){ //读取文件内容保存到resultStr String resultStr = null; File file = new File(Environment.getExternalStorageDirectory(),fileName); try { FileInputStream fileInputStream = new FileInputStream(file); byte[] b = new byte[fileInputStream.available()]; fileInputStream.read(b); resultStr = new String(b); if(fileInputStream != null){ fileInputStream.close(); } } catch (Exception e) { e.printStackTrace(); System.out.println("读文件出错"); } //将读取的String结果转化成List<> List<Map<String, Object>> tempList = new ArrayList<Map<String, Object>>(); try { JSONArray jsonArray = new JSONArray(resultStr); if (jsonArray.length()>0) { for (int i=0;i<jsonArray.length();i++) { JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString()); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("who", jsonObject.get("who")); map.put("chat", jsonObject.get("chat")); tempList.add(map); } } } catch (JSONException e){ e.printStackTrace(); System.out.println("转化list出错"); } return tempList; }调用函数形式,传入要读取的文件名,直接返回相应的List<Map<String,Object>>类型数据:
private List<Map<String, Object>> recordList = new ArrayList<Map<String,Object>>(); recordList = getDataFromSDcard("chatRecord.txt");