如何保存Uri类型路径至平面文件并恢复后赋值给ImageView
保存Uri路径到平面文件并恢复用于ImageView显示
已实现的保存逻辑
将输入字符串与Uri转为字符串后用#分隔,写入MisComidas.txt文件,代码如下:
private fun saveToFile(){ try { val archivo = OutputStreamWriter(openFileOutput("MisComidas.txt", MODE_APPEND)) val text= binding.etComida.text.toString()+"#"+imgUri.toString()+"\n" archivo.write(text) archivo.flush() archivo.close() } catch (_: IOException) { } Toast.makeText(this, "Comida-->${dataSet.size} Guardada Correctamente" ,Toast.LENGTH_SHORT).show() }
读取并恢复Uri的实现
读取文件时将分割后的字符串转回Uri类型,添加到数据集供RecyclerView加载显示图片,读取方法代码如下:
private fun readFile(){ if (fileList().contains("MisComidas.txt")) { try { var texto = "" val archivo = InputStreamReader(openFileInput("MisComidas.txt")) val br = BufferedReader(archivo) var linea = br.readLine() while (linea != null) { val pos1 = linea.indexOf("#") val str = linea.substring(0, pos1) val str1 = (linea.substring(pos1+1)).toUri() dataSet.add(ComidaData(str,str1)) texto = texto + linea + "\n" linea = br.readLine() } br.close() archivo.close() } catch (_: IOException) { } } }
内容的提问来源于stack exchange,提问作者CVtec
相关产品推荐
相关产品推荐

