2017.12.25 Android data storage solution

1. Persistence technology:

Data persistence: a technology that saves the data in the memory to a file so that the device can be used normally after shutdown or restart;

The cost of switching between memory state and persistent state: CPU, file reading, file writing, kernel state switching

2.Android built-in persistence technology:

(1) file system;

(2) Shared Preferences

(3)SQLite

3. How to use the file system: file persistence

How to save data to a file:

How to read data from a file:

Note: The data is placed in the data/data/packagename/files folder by default, and it will be warned by the system if it is placed in other paths

Example of file writing and reading:

(1) Layout file:

(2) Java program for writing and reading files:

2.1 Define variables and get layout ID:

public void write(){<!-- --><br>    String data="Merry Christmas, I wish you all a smooth exam!";<br>    FileOutputStream out=null;<br>    BufferedWriter writer=null;<br>    try{<!-- --><br>        out=openFileOutput("data.log", Context.MODE_PRIVATE);<br>        writer=new BufferedWriter(new OutputStreamWriter(out));<br>        writer. write(data);<br>    }catch (IOException e){<!-- --><br>        e.printStackTrace();<br>    }finally {<!-- --><br>        try{<!-- --><br>            if (writer!=null){<!-- --><br>                writer. close();<br>            }<br>        }catch(IOException e){<!-- --><br>            e.printStackTrace();<br>        }<br>    }<br>}

2.2 button binding write file function event:

 WriteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                write();
            }
        });

(3) Define the permission to write to the file:

(4) Java program for reading files:

 public String Read(){ //return a String
        FileInputStream in=null; //Read the data stream of the file
        BufferedReader reader=null;
        StringBuilder content=new StringBuilder();
        try {
            in=openFileInput("data. log");
            reader=new BufferedReader(new InputStreamReader(in));
            String line="";
            while ((line=reader. readLine())!=null){
                content.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        } finally {
            if(reader!=null){
               try {
                   reader. close();
               }catch (IOException e){
                   e.printStackTrace();
               }
            }
        }

        return content.toString();
    }

3.1 Button binding to read file system data:

 ReadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String str=Read();
                Toast.makeText(MainActivity.this,str,Toast.LENGTH_LONG).show();
            }
        });
    }

4. How to use SharedPreferences:

(1) Non-relational data

(2) Stored in the form of Key-Value key-value pairs;

(3) In essence, an XML file is maintained, and data is stored and read on this file;

Example: Just look at the Java program code directly, everything else is the same

 public void write(){ //no return value
        SharedPreferences.Editor editor=getSharedPreferences("data",MODE_PRIVATE).edit();
        //The first parameter: the stored file name, the second parameter is the open mode
        editor.putString("username","chunyu");
        editor. putString("password","0321");
        editor. apply();

    }

Button bindings write events to SharedPreferences:

 WriteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                write();
            }
        });

The result of writing:

5. How to use SQLite:

(1) A relational database

(2) Android, windows and Linux can be used directly

(3) Free and open source

(4) In the case of a small amount of data, it is a good choice

example:

layout file:

JAVA program that uses SQLite to store data:

 private Button createButton;
   private DataBaseHelper dbHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R. layout. activity_main);
        //Database class instantiation, instantiate database access
        dbHelper=new DataBaseHelper(this,"userdatabase,db",null,1); //The second parameter is the name of the database

        createButton=(Button)findViewById(R.id.creatButton);
        createButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dbHelper.getWritableDatabase(); //
            }
        });
    }
    public class DataBaseHelper extends SQLiteOpenHelper{<!-- -->
        public static final String Create_SQL="create table userinfo(id integer primary key autoincrement, username text, password text)";

        private Context mContext;

        public DataBaseHelper(Context context, String name, SQLiteDatabase. CursorFactory factory, int version){
            super(context, name, factory, version);
            mContext=context;
        }

        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) { // directly rewrite the method of the parent class
            sqLiteDatabase.execSQL(Create_SQL);
            Toast.makeText(mContext,"Create database successfully",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

        }
    }

operation result: