Android Month 2_Day8_Shared Preferences Storage + SD Card Storage
SharedPreferences
Shared Preferences, referred to as Sp (hereinafter referred to as Sp), is a lightweight data storage method that maps in the way of Key/value, and ultimately exists in xml format in the mobile phone's / data/data/package_name/shared_prefs/directory.
Sp is usually used to record some parameter configurations, behavior tags, etc. Because it's easy to use, most developers are happy to use it!
But please note: Do not use Sp to store large amounts of data, and do not let your SP file super large, otherwise it will greatly affect the application performance, or even ANR (program unresponsive)
Characteristic:
Keep a small amount of data in a very simple format. Store five original data types: boolean, float, int, long, String
For example, the application's various configuration information (such as whether to turn on sound effects, whether to use vibration effects, small game player points, etc.), remember the password function, music player playback mode.
Skills: (1) How to store data (2) How to obtain data
Usage
Step 1: Get the SharedPreferences object getSharedPreferences("name of file", "type of file");
Context.MODE_PRIVATE: Specifies that the Shared Preferences data can only be read and written by the application
(2)MODE_APPEND: Check whether the file exists, add content to the file if it exists, or create a new file.
The following is not recommended for use
Context. MODE_WORLD_READABLE: Specifies that the Shared Preferences data can be used by others
The application reads, but cannot write.
(4) Context, MODE_WORLD_WRITEABLE: Specifies that the Shared Preferences data can be written by other applications, but not read.
Step 2: Get the SharedPreferences.Editor edit object
SharedPreferences.Editor editor=sp.edit();
Step 3: Add data
editor.putBoolean(key,value)
editor.putString()
editor.putInt()
editor.putFloat()
editor.putLong()
Step 4: Submit data editor.commit() or apply () (recommended for this. Asynchronous submission)
Editor's other method: editor.clear() clears the data editor.remove(key) removes the data corresponding to the specified key
Write data
SharedPreferences preferences = getSharedPreferences("write", MODE_PRIVATE); //TODO 2: Getting Edit Objects SharedPreferences.Editor editor = preferences.edit(); //TODO 3: Writing Data editor.putString("username","Write data"); editor.putInt("age",18); editor.putBoolean("isMan",false); editor.putFloat("price",12.4f); editor.putLong("id",5425054250l); //TODO 4: Submit data editor.commit();
Reading data
Step 1: Get the SharedPreferences object getSharedPreferences("name of file", "type of file");
Step 2: Read the data String msg = sp.getString(key,defValue);
//TODO 1: Get the SharedPreferences object //Parametric 1 xml file name parameter 2 mode MODE_PRIVATE specifies that the Shared Preferences data can only be read and written by the application SharedPreferences preferences = getSharedPreferences("write", MODE_PRIVATE); //TODO 2: Direct Reading //Give default value when parameter one key parameter two cannot be found String username=preferences.getString("username",""); int age=preferences.getInt("age",0); boolean isMan=preferences.getBoolean("isMan",false); float price=preferences.getFloat("price",0.0f); long id=preferences.getLong("id",0l); Toast.makeText(this, username+":"+age+":"+isMan+":"+price+": "+id, Toast.LENGTH_SHORT).show();
Use Case 1
xml layout
<?xml version="1.0" encoding="utf-8"?> <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=".Main2Activity" android:orientation="vertical" android:gravity="center"> <EditText android:layout_marginLeft="50dp" android:layout_marginRight="50dp" android:id="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" /> <EditText android:layout_marginLeft="50dp" android:layout_marginRight="50dp" android:id="@+id/password" android:inputType="textPassword" android:layout_width="match_parent" android:layout_height="wrap_content" /> <RelativeLayout android:layout_marginLeft="50dp" android:layout_marginRight="50dp" android:layout_width="match_parent" android:layout_height="wrap_content"> <CheckBox android:layout_alignParentLeft="true" android:id="@+id/cb_remember" android:text="Keep passwords in mind" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:layout_alignParentRight="true" android:id="@+id/login" android:text="Sign in" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> </LinearLayout>
java code
private EditText username; private EditText password; private CheckBox cbRemember; private Button login; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); init(); } private void init() { username = findViewById(R.id.username); password = findViewById(R.id.password); cbRemember = findViewById(R.id.cb_remember); login = findViewById(R.id.login); SharedPreferences preferences = getSharedPreferences("loadStory", MODE_PRIVATE); String name = preferences.getString("name", ""); String pwd = preferences.getString("password", ""); Boolean isChecked = preferences.getBoolean("isChecked", false); if(name!=null&&password!=null&&isChecked!=false){ username.setText(name); password.setText(pwd); cbRemember.setChecked(true); } login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(cbRemember.isChecked()){ SharedPreferences preferences = getSharedPreferences("loadStory", MODE_PRIVATE); SharedPreferences.Editor edit = preferences.edit(); edit.putString("name",username.getText().toString()); edit.putString("password",password.getText().toString()); edit.putBoolean("isChecked",true); edit.commit(); }else { SharedPreferences preferences = getSharedPreferences("loadStory", MODE_PRIVATE); SharedPreferences.Editor edit = preferences.edit(); edit.putBoolean("isChecked",false); edit.putBoolean("load", true); edit.commit(); } } });
File store:
Internal file storage
openFileOutput
It's no different from java operating files. Only the path is unique
FileInputStream fileInputStream = null; try { fileInputStream= openFileInput("aa.json"); byte[] b = new byte[1024]; int len = 0; while((len = fileInputStream.read(b)) != -1){ Log.i(TAG, "onClick: "+new String(b,0,len)); } } catch (Exception e) { e.printStackTrace(); }
External File Storage (SD Card)
1.SD Card Introduction:
General Mobile File Management Root Path/storage/emulated/0/or/mnt/shell/emulated/0
2. Important code:
(1) Environment. getExternal Storage State (); // Judging SD Card
(2) Environment. getExternal Storage Directory (); Get the root directory of the SD card
(3) Environment.getExternal Storage PublicDirectory (Environment.DIRECTORY_pictures); Get the SD Card Public Directory pictures folder
3. It is necessary to add the right to read and write SD cards.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
private Button login; private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String externalStorageState = Environment.getExternalStorageState(); Log.i(TAG, "onCreate: "+externalStorageState); File externalStorageDirectory = Environment.getExternalStorageDirectory(); Log.i(TAG, "onCreate: "+externalStorageDirectory.toString()); File externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); Log.i(TAG, "onCreate: "+externalStoragePublicDirectory); login = findViewById(R.id.login); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "onClick: "); //Runtime permissions requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},100); if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //Get the SD Kagan path: File file = Environment.getExternalStorageDirectory(); FileOutputStream out = null; try { //Create an output stream out = new FileOutputStream(new File(file, "json.txt")); out.write("My brother".getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode == 100){ if(grantResults != null && grantResults[0] == PackageManager.PERMISSION_GRANTED){ Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(this, "No way.", Toast.LENGTH_SHORT).show(); } } } }
Improved code
Write the file operation into a callback method that agrees to authorize.
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ File file = Environment.getExternalStorageDirectory(); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(new File(file,"aa.json")); fileOutputStream.write("aaa".getBytes()); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } } }else{ Toast.makeText(this, "No privileges", Toast.LENGTH_SHORT).show(); } }