Android file storage and SharedPreference storage

Today I
am studying Chapter 6 and I have been abandoned for a few days. Think about it or read a book. There is no other better way to learn.
Still not watching the video to learn.

Data storage solution-detailed persistence technology

The Android system mainly provides three ways to simply realize the data persistence function:

1.文件存储

2.SharedPreference存储

3.数据库存储

Of course, in addition to these three methods, you can also save the data in the SD card of the phone, but it is easier to save the data using files, SharedPreferences or databases, and it will be more secure than saving the data in the SD card. .

File storage

Suitable for storing some simple text data or binary data.

If you want to use file storage to save some more complex text data, you need to define a set of your own format specifications, so that you can easily re-parse the data from the file later.

Store data in a file

The Context class provides an openFileOutput() method for storing in the specified file.

The openFileOutput() method receives two parameters:

The first parameter is the file name, which is used when the file is created. Note that the file name specified here cannot include a path, because all files are stored in the /data/data//files/ directory by default .

The second parameter is the operating mode of the file. There are two main modes to choose from, MODE_PRIVATE and MODE_APPEND.

MODE_PRIVATE is the default operation mode, which means that when the same file name is specified, the written content will overwrite the content in the original file.

MODE_APPEND means that if the file already exists, add content to the file, and create a new file if it does not exist.

What the openFileOutput() method returns is a FileOutputStream object. After getting this object, you can use the JAVA stream to write data to the file.

public void save(){
    
    
	String data = "Data to save";
	FileOutputStream out = null;
	BufferedWriter writer = null;
	try{
    
    
		out = OpenFileOutput("data",Context.MODE_PRIVATE);
		writer = new BufferedWriter(new OutputStreamWriter(out));
		writer.write(data);
	}catch(IOException e){
    
    
		e.printStackTrace();
	}finally{
    
    
		try{
    
    
			if(writer!=null){
    
    
				writer.close();
			}
		}catch(IOException e){
    
    
			e.printStackTrace();
		}
	}
}

Here is a brief review of the java flow:

1. Operate the file :FileInputStream(字节输入流),FileOutputStream(字节输出流),FileReader(字符输入流),FileWriter(字符输出流)

2. Buffered stream:BufferedInputStream,BufferedOutputStream,BufferedReader,BufferedWriter,是带缓冲区的处理流,缓冲区的作用的主要目的是:避免每次和硬盘打交道,提高数据访问的效率。

3. Conversion flow InputStreamReader/OutputStreamWriter,把字节转化成字符。

Read data from file

Similar to storing data in a file, the Context class also provides an openFileInput() method for reading data from a file.

openFileInput() only receives one parameter, which is the name of the file to be read, and then the system will automatically go to the /data/data/files/ directory to load this file

And return a fileInputStream object, after obtaining this object, the data can be read out through the Java stream.

public String load{
    
    
	FileInputStream in = null;
	BufferedReader reader = null;
	StringBuilder content = new StringBuilder();
	try{
    
    
		in = OpenFileInput("data");
		reader = new BufferedRead(new InputStreamReader(in));
		String line = "";
		while((line = reader.readline())!= null){
    
    
			content.append(line);
		}
	}catch(IOException){
    
    
		e.printStackTrace();
	}finally{
    
    
		if(reader != null ){
    
    
			try{
    
    
				reader.close();
			}catch(IOException){
    
    
					e.printStackTrace();
				}
		}
	}
	return content.toString();
	}

First obtain a FileInputStream object through the openFileInput() method, and then use it to construct an InputStreamReader object, and then use InputStreamReader to construct a BufferedReader object, so that we can read line by line through BufferedReader, and read all the files in the file. All the text content of is read out and stored in a StringBuilder object, and finally the read content is returned.

SharedPrefences storage

不同于文件的存储方式,SharePreference是使用键值对的方式来存储数据的。
也就是说,当保存一条数据的时候,需要给这条数据提供一个对应的键,这样在数据读取的时候就可以通过这个键把相应的值取出来。
而且SharePreference还支持多种不同的数据类型存储,如果存储的数据类型是整形,那么读取出来的数据也是整形的。如果存储的数据是一个字符串,
那么读取出来的数据仍然是字符串。

Store data to SharePreference

To use SharePreference to store data, you first need to get the SharedPreferences object.

Android mainly provides three methods for obtaining SharedPreference objects.

1. The getSharedPreferences() method in the Context class

This method receives two parameters. The first parameter is used to specify the name of the SharedPreference file. If the specified file does not exist, it will be created. The SharePreference files are stored in the /data/data//shared_prefs/ directory.

The second parameter is used to specify the operating mode. Currently, only MODE_PRIVATE is available for selection. It is the default operating mode and has the same effect as directly passing in 0. It means that only the current application can read and write this SharedPreference file.

Several other modes are obsolete.

2. The getPreferences() method in the Activity class

This method is similar to the getSharedPreferences() method in Context, but it only receives one operation parameter, because when using this method, the currently active class name is automatically used as the file name of the SharedPreference.

3. The getDefaultSharedPreference() method in the PreferenceManager class

This is a static method. It receives a Context parameter and automatically uses the package name of the current application as a prefix to name the SharedPreference file. After obtaining the SharedPreference object, you can start storing data in the SharedPreference file.

Three steps to store data:

(1) Call the edit() method of the SharedPreference object to obtain a SharedPreference.Editor object

(2) Add data to the SharedPreference.Editor object. For example, to add a Boolean data is to use the putBoolean() method, to add a string, use the putString() method, and so on.

(3) Call the apply() method to submit the added data to complete the data storage operation.

example:

Create a new SharedPrenferenceTest project, and then modify the code in activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="net.nyist.lenovo.sharedpreferencestest.MainActivity">
    
    <Button
    android:id="@+id/btn_SaveData"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Save data"
    />
    </LinearLayout>

Then modify the code of MainActivity:

 public class MainActivity extends AppCompatActivity {
    
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button saveData = (Button) findViewById(R.id.btn_SaveData);
    saveData.setOnClickListener(new View.OnClickListener() {
    
    
	//给按钮注册一个点击事件
    @Override
    public void onClick(View v) {
    
    
    SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
    //指定文件名为data,并且得到SharedPreference.Editor对象。
	editor.putString("name","Tom");
    editor.putInt("age",18);
    editor.putBoolean("married",false);
	//添加三个不同类型的数据
    editor.apply();
	//最后提交
    }
    });
    }
    }

Read data from SharedPrenferences

The SharedPrenferences object provides a series of get methods for reading the stored data.

Each get method corresponds to a put method in SharedPrenferences.Editor.

These get methods all accept two parameters:

The first parameter is the key, and the corresponding value can be obtained by passing in the key used when storing the data.

The second parameter is the default value, which means that the default value will be returned when the passed-in key cannot find the corresponding value.

Still the example just now:

Modify the code in activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="net.nyist.lenovo.sharedpreferencestest.MainActivity">
    
    <Button
    android:id="@+id/btn_SaveData"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Save data"
    />
    
    <Button
    android:id="@+id/restore_data"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Restore data"
    />
    
    </LinearLayout>

Here add a button to restore data, and then modify the code in MainActivity:

 public class MainActivity extends AppCompatActivity {
    
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    		······
    Button restoreData = (Button) findViewById(R.id.restore_data);
    restoreData.setOnClickListener(new View.OnClickListener() {
    
    
    @Override
    public void onClick(View v) {
    
    
    SharedPreferences pres = getSharedPreferences("data",MODE_PRIVATE);
	//首先通过getSharedPreferences()方法得到了SharedPreferences对象
    int age = pres.getInt("age",0);
    String name = pres.getString("name","");
    boolean  married = pres.getBoolean("married",false);
    Log.d("MainActivity","name is"+name);
    Log.d("MainActivity","age is "+age);
    Log.d("MainActivity","married is "+married);
    }
    });
    }
    }

Below is a screenshot of the result:

Store data to SharedPreference
Stored successfully

Read data

Read successfully

Guess you like

Origin blog.csdn.net/i_nclude/article/details/77618690