Android Development and Realization of File Storage Function

  • 2021-12-05 07:14:15
  • OfStack

In this paper, we share the specific code of Android development and file storage for your reference. The specific contents are as follows

This program has only one Activity and only one Edittext in Activity. The function implemented is to store the contents of EditText in a file before Activity is destroyed, and when Activity is created, read the contents from this file and write them in EditText. The code is as follows, loading data in onCreate and saving data in onDestroy.

MainActivity.kt


package com.example.filetest

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import java.io.*
import java.lang.StringBuilder

class MainActivity : AppCompatActivity() {
 override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_main)

  editText.setText(loda())
 }

 override fun onDestroy() {
  super.onDestroy()
  save(editText.text.toString())
 }

 private fun save(inputText:String){
  try {
   // This function takes two arguments, the file name and the open mode 
   // The default storage path for the function is /data/data/<package name>/file
   // The open mode is mainly MODE_APPEND( Additional) and MODE_PRIVATE( Overlay) 
   val output = openFileOutput("data", Context.MODE_PRIVATE)
   val write = BufferedWriter(OutputStreamWriter(output))
   write.use {
    it.write(inputText)
   }
  }catch (e:IOException){
   e.printStackTrace()
  }
 }

 private fun loda():String{
  val result = StringBuilder()
  try {
   val input = openFileInput("data")
   val reader = BufferedReader(InputStreamReader(input))
   reader.use {
    reader.forEachLine {
     result.append(it)
    }
   }
  }catch (e : IOException){
   e.printStackTrace()
  }
  return result.toString()
 }
}

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent">

 <EditText
  android:id="@+id/editText"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:hint=" Please enter 1 Duan Hua "/>

</LinearLayout>

Related articles: