Android Development Notes Android Data storage method (I)

  • 2020-12-18 01:54:42
  • OfStack

For the development platform, if there is good support for data storage, then the development of applications will be a great boost.

Generally speaking, there are three ways to store data: one is a file, one is a database, and one is a network. File and database may use a little more than 1, the file is more convenient to use, the program can define its own format; Database with a little bit of trouble lock 1, but it has its advantages, such as in the mass data performance is superior, there is a query function, can be encrypted, can be locked, can cross applications, cross-platform and so on; Network is used for more important things, such as scientific research, exploration, aviation and other real-time data collected need to be immediately transmitted through the network to the data processing center for storage and processing, and there is a real-time demand.

For the Android platform, it is stored in one of the following ways, which are classified as files, databases and networks in general. However, I think it can be subdivided into the following 5 ways in terms of storage target:

1.1 way

Shared Preferences: Mainly used to save the system configuration information of the program. Used to store "ES13en-ES14en paires". It is generally used to save the information set at the time the program is started, so that the information set in the previous time is retained at the next time the program is started.
xml: Save complex data, such as text message backups.

3.Files: Save information as a file. You can get or save relevant information by reading or writing to a file.

SQLite: Save information in the form of a database. SQLite is an open source database system.

NetWork: Save data on the network.

1.2 the difference between

1. Shared Preferences:

Android provides a mechanism for storing 1 simple configuration information, such as 1 default welcome, login username and password, etc. It is stored as a key-value pair.

SharedPreferences is automatically saved as a file in XML format and expanded to /data/data/ in File Explorer in DDMS < packagename > Under /shared_prefs, take your own project as an example, you can see a file called SETTING_Infos.xml

2. Files

In Android, it provides openFileInput and openFileOuput methods to read files on the device. Here is an example code, as shown below:


String FILE_NAME = "tempfile.tmp"; // Determine the filename of the file you want to manipulate 
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE); // Initialize the 
FileInputStream fis = openFileInput(FILE_NAME); // Create write streams  

The two methods in the code above only support reading files in the application directory; reading files not in its own directory will throw an exception. It is important to note that if the file specified when calling FileOutputStream does not exist, Android creates it automatically, so there is no need to determine if the file exists. In addition, by default, the content of the original file will be overwritten when writing. If you want to attach the content of the new write to the content of the original file, you can specify its mode as ES74en. MODE_APPEND.

3. SQLite

SQLite is a standard database with Android, it supports SQL statements, it is a lightweight embedded database

4. NetWork:

Upload data to the network

Supplement:

The bottom layer of Shared Preferences uses xml. xml can also save data, but Shared Preferences can only save key-value pairs, while xml can save complex data

2. At the bottom of Content provider, Sqlite database is still used, which is another way to calculate it.

1.3 example

1. Shared Preferences:

Small case: the user enters the account password, clicks the login button, and saves the account and password persistently while logging in

Store your account password with SharedPreference

The & # 8226; Write the data in SharedPreference


// get 1 a SharedPreference object 
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
// Get to the editor 
Editor ed = sp.edit();
// Write the data 
ed.putString("name", name);
ed.commit(); 

Note: Remember here that put must be completed under commit1.

The & # 8226; Data from SharedPreference


SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
// from SharedPreference To get the data 
String name = sp.getBoolean("name", ""); 

The & # 8226; Code:

The & # 8226; Layout file


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" 
android:orientation="vertical"
>
<EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint=" Please enter the user name " 
/>
<EditText
android:id="@+id/et_pass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint=" Please enter your password. " 
android:inputType="textPassword" 
/>
<RelativeLayout 
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<CheckBox 
android:id="@+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Remember the username and password "
android:layout_centerVertical="true"
/>
<Button 
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" The login "
android:layout_alignParentRight="true"
android:onClick="login"
/>
</RelativeLayout>
</LinearLayout> 

The & # 8226; java code


package com.bokeyuan.sharedpreference;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.et_name);
et_pass = (EditText) findViewById(R.id.et_pass);
// get SharedPreferences object 
SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
// from SharedPreferences Take out the data in 
String name = sp.getString("name", "");
String pass = sp.getString("pass", "");
et_name.setText(name);
et_pass.setText(pass);
}
public void login(View v){
String name = et_name.getText().toString();
String pass = et_pass.getText().toString();
// get SharedPreferences object 
SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
// Store the data SharedPreferences
Editor ed = sp.edit();
ed.putString("name", name);
ed.putString("pass", pass);
// submit 
ed.commit();
}
} 

2. Files

Small case: The user enters the account password, tick "Remember account password", click the login button, and persist to save the account and password while logging in

The & # 8226; Read and write files in internal storage (RAM)

The & # 8226; Layout file: Same as the layout above

The & # 8226; java code:


package com.bokeyuan.rwinrom;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.et_name);
et_pass = (EditText) findViewById(R.id.et_pass);
readAccount();
}
@SuppressLint("ShowToast") public void login(View v){
String name = et_name.getText().toString();
String pass = et_pass.getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
if(cb.isChecked()){
// The specified Android The path of the internal storage space 
// File file = new File("data/data/com.bokeyuan.rwinrom/info.txt");
// return 1 a File Object whose path is: data/data/com.bokeyuan.rwinrom/files/
// File file = new File(getFilesDir(), "info.txt");
// return 1 a File Object whose path is: data/data/com.bokeyuan.rwinrom/cache/
File file = new File(getCacheDir(), "info.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write((name + "##" + pass).getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// A prompt box pops up to prompt the user to log in successfully 
Toast.makeText(this, " Log in successfully ", 0).show();
}
public void readAccount(){
// The specified Android The path of the internal storage space 
// File file = new File("data/data/com.bokeyuan.rwinrom/info.txt");
// File file = new File(getFilesDir(), "info.txt");
File file = new File(getCacheDir(), "info.txt");
if(file.exists()){
try {
FileInputStream fis = new FileInputStream(file);
// Convert byte streams into character streams 
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String text = br.readLine();
String[] s = text.split("##");
et_name.setText(s[0]);
et_pass.setText(s[1]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

The & # 8226; Read and write files in external storage space (SD card)

The & # 8226; Layout file: Same as the layout above

The & # 8226; java code:


package com.bokeyuan.rwinsd;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import com.bokeyuan.rwinsd.R;
import android.os.Bundle;
import android.os.Environment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.et_name);
et_pass = (EditText) findViewById(R.id.et_pass);
readAccount();
}
public void login(View v){
String name = et_name.getText().toString();
String pass = et_pass.getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
if(cb.isChecked()){
// detection sd Is the card currently available 
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
// File file = new File("sdcard/info.txt");
// return 1 a file Object that contains the path sd The true path of the card 
File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write((name + "##" + pass).getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
Toast.makeText(this, "sd The card is not available ", 0).show();
}
}
// A prompt box pops up to prompt the user to log in successfully 
Toast.makeText(this, " Log in successfully ", 0).show();
}
public void readAccount(){
// File file = new File("sdcard/info.txt");
File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
if(file.exists()){
try {
FileInputStream fis = new FileInputStream(file);
// Convert byte streams into character streams 
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String text = br.readLine();
String[] s = text.split("##");
et_name.setText(s[0]);
et_pass.setText(s[1]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} 

Note:

The & # 8226; / / this api will write file data/data/com itheima. permission/files/folder
•FileOutputStream fos = openFileOutput("info1.txt", MODE_PRIVATE) ;
The & # 8226; / / this api will read the file data/data/com itheima. permission/files/folder
•FileOutputStream fos = openFileOutput("info1.txt", MODE_PRIVATE) ;

The & # 8226; So, API comes with Android in the future. Here are some small examples of openFileOutput4 patterns:

The & # 8226; Four modes of openFileOutput


•MODE_PRIVATE = 0:       -rw-rw----
•MODE_APPEND = 32768:    -rw-rw----
•MODEWORLDREADABLE = 1: -rw-rw-r--
•MODEWORLDWRITEABLE = 2: -rw-rw--w-

Context.MODE_PRIVATE: Is the default mode, which means that the file is private data and can only be accessed by the application itself. In this mode, the contents of the file are overwritten by the contents of the file. If you want to append the contents of the new writing to the original file, you can use ES215en.MODE_APPEND.

Context.MODE_APPEND: The schema checks if a file exists, appends it to the file, or creates a new file.
Context.MODE_WORLD_READABLE and ES228en.MODE_ES230en_ES231en are used to control whether other applications have permission to read and write the file.
MODE_WORLD_READABLE: means that the current file can be read by other applications; MODE_WORLD_WRITEABLE: Indicates that the current file can be written by another application.

The & # 8226; Note:

The & # 8226; In Android, each application is a separate user
•drwxrwxrwx
The & # 8226; Bit 1: d for folder, - for files
The & # 8226; Bits 2-4: rwx, which represents the permissions of the file's owner user (owner) • Read r:
The & # 8226; w: write
The & # 8226; x: perform
The & # 8226; Bits 5-7: rwx, which represents the permissions of the user (grouper) who is in the same group as the user who owns the file
The & # 8226; Bits 8-10: rwx, indicating the permissions that users of other user groups (other) have on the file

The & # 8226; Layout file:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" 
android:orientation="vertical"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Create a file 1" 
android:onClick="click1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Create a file 2" 
android:onClick="click2"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Create a file 3" 
android:onClick="click3"
/>
</LinearLayout> 

The & # 8226; Code:


package com.bokeyuan.permission;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
@SuppressLint("WorldReadableFiles")
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click1(View v){
// this api It writes to the file data/data/com.bokeyuan.permission/files/ folder 
try {
FileOutputStream fos = openFileOutput("info1.txt", MODE_PRIVATE) ;
fos.write(" This file is private data and can only be accessed by the application itself ".getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void click2(View v){
// this api It writes to the file data/data/com.bokeyuan.permission/files/ folder 
try {
@SuppressWarnings("deprecation")
FileOutputStream fos = openFileOutput("info2.txt", MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE) ;
fos.write(" The current file can be read or written by another application ".getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void click3(View v){
// this api It writes to the file data/data/com.bokeyuan.permission/files/ folder 
try {
@SuppressWarnings("deprecation")
FileOutputStream fos = openFileOutput("info3.txt", MODE_WORLD_WRITEABLE) ;
fos.write(" The current file can be written by another application ".getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} 

The & # 8226; Obtain SD card remaining capacity:

The & # 8226; Sometimes when reading or writing a file, you need to determine the remaining capacity of the SD card before writing. The following small example refers to API at the bottom of Android system to obtain the remaining capacity of SD card.

The & # 8226; Layout file:


// get 1 a SharedPreference object 
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
// Get to the editor 
Editor ed = sp.edit();
// Write the data 
ed.putString("name", name);
ed.commit(); 
0

The & # 8226; Java code:


// get 1 a SharedPreference object 
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
// Get to the editor 
Editor ed = sp.edit();
// Write the data 
ed.putString("name", name);
ed.commit(); 
1

The above has introduced you to the Android development notes Android data storage method (1) related knowledge, I hope this article will be helpful to you. In the next article, I will give android development notes on how to store data in android (2). If you are interested, please click here for details.


Related articles: