—- Data storage

Data persistence is the preservation of transient data to memory devices so that it will not disappear after the phone or computer is turned off.

Android provides three simple data persistence features:

The text is stored

It is the most basic data storage method of Android, without any formatting of the stored content, it is kept intact. It is more suitable for storing some simple text data and some binary data.

Store the data in a file

The Context class provides an openFileoutput() method to store data to the specified file

// The first argument is to pass in the file name. Be careful not to include the path to the file name
// The second parameter file operation mode can be passed in two ways:
//MODE_PRIVATE: If you specify the same file name, the new data will overwrite the original data
 //MODE_APPEND: If the specified file already exists, it will append to the file and not overwrite it
val output=openFileoutout("File name", file operation mode)Copy the code

Example code is as follows:

 fun sava(inputext:String){
 val output=openFileoutput("data",MODE_PRIVATE)
 val writer=BufferedWirter(OutputStreamWirter(output)){
 wirter.use{
   it.write(inputex)
 }
 }catch (e:IOException){
     e.printStackTrace()
   }
 }
Copy the code

Now create a new project and modify the activity.man. XML code. Here we just add an EditText and enter the text

<? xml version="1.0" encoding="utf-8"? > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  >
    <EditText
         android:id="@+id/editTest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Type something here"/>

</LinearLayout>

Copy the code

At this point, if you run the program, there’s a text box, you type in something, you press Back, and the data is lost, because it’s stored in memory and it’s instantaneous, so we have to store it in a file before we reclaim it.

To modify the ManActivity code, we first override the onDestroy method to ensure that it is called before the Activity is destroyed.

package com.example.activitytest

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.EditText
import android.widget.Toast
import java.io.*
import java.lang.StringBuilder

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

    }

    override fun onDestroy(a) {
        super.onDestroy()
        val editText:EditText=findViewById(R.id.editTest)
        // Read the contents of the text box
         val inputText=editText.text.toString()
        / / store
          sava(inputText)
    }
    private fun sava(outext:String){
        try {
            val puttex=openFileOutput("data",Context.MODE_PRIVATE)
            val writer=BufferedWriter(OutputStreamWriter(puttex))
            writer.use {
                it.write(outext)
            }
        }catch (e:IOException){
             e.printStackTrace()
        }

    }
}
Copy the code

At this time in the running program, input some content in the text box, press the Back key to close the program, how to check whether the success of the Device File Explorer view, generally in the data/data/com.example.(project name).file/ directory, view, generate a data File.

Read data from a file

The Context class provides an openFileInput method to read, which takes a filename as an argument, and then the system automatically loads the file into the data/data//file/ directory, and returns an FileInputStream object. The data is then read as a stream

package com.example.activitytest

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.EditText
import android.widget.Toast
import java.io.*
import java.lang.StringBuilder

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       val inputext=load()
        if (inputext.isNotEmpty()){
            val editText:EditText=findViewById(R.id.editTest)
            editText.setText(inputext)
            editText.setSelection(inputext.length)
            Toast.makeText(this."Restoring ",Toast.LENGTH_SHORT).show()
        }
    }
  private fun load(a):String{
      val content=StringBuilder()
      try {
          val intput=openFileInput("data")
          val read=BufferedReader(InputStreamReader(intput))
          read.use {
              read.forEachLine {
                  content.append(it)
              }
          }
      }catch (e:IOException){
          e.printStackTrace()
      }
     return content.toString()
  }

}
Copy the code

Now re-run the program, for example, enter Hello,World in the text box, and press Back to exit. Re-run the program Hello,World still exists

ShardPreferences storage

ShardPreferences ShardPreferences is used to store data by key value. If no data is saved, the corresponding key value will be given. When data is read, it will be read by key value and different data types can be stored.

Instance as follows

Create a new project and modify the activity.man. XML code to add a Button control

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

   
<Button
    android:id="@+id/savabutton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Sava Data"/>
</LinearLayout>

Copy the code

Then set a click event for the button in the ManActivity

package com.example.activitytest2

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val savabutton:Button=findViewById(R.id.savabutton)
        savabutton.setOnClickListener {
            val edior=getSharedPreferences("data",Context.MODE_PRIVATE).edit()
            edior.putString("name"."Tom")
            edior.putInt("Int".232)
            // Add data submission to complete database storage operation
            edior.apply()
        }
    }
}
Copy the code

Run the program, click the Sava Data button to save the Data, save the Data, and the SharedPreferences file uses XML format to manage the Data

Read data from ShardPreferences

Modify the activity.man.xml code on your original project to add a button that reads data from the ShardPreferences file

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


<Button
    android:id="@+id/savabutton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Sava Data"/>
  
    <Button
        android:id="@+id/retoreButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Restore Data"/>
</LinearLayout>

Copy the code

Next, modify the ManActivity code

package com.example.activitytest2

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import java.time.LocalDate

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val savabutton:Button=findViewById(R.id.savabutton)
        savabutton.setOnClickListener {
            val edior=getSharedPreferences("data",Context.MODE_PRIVATE).edit()
            edior.putString("name"."Tom")
            edior.putInt("age".23)
            // Add data submission to complete database storage operation
            edior.apply()
        }

      
        val restrictTo:Button=findViewById(R.id.retoreButton)
         restrictTo.setOnClickListener {
              // Use this method to get the SharedPreferences object
             val read=getSharedPreferences("data",Context.MODE_PRIVATE)
              // Call their getString,getInt methods to retrieve the previously stored values
             val name=read.getString("name"."")
             val age=read.getInt("age".0)
           / / print
             Log.d("MainActivity"."name is $name")
             Log.d("ManinActivity"."age is $age")}}}Copy the code

Run the program and click the RESTORE DATA button to get the following effect