Android briefly introduces SharedPreference, internal files, and sdcard data storage,

Source: Internet
Author: User

Android briefly introduces SharedPreference, internal files, and sdcard data storage,

SharedPreference

Store simple data in xml structure and store it in the data/package name/shared_prefs folder

Usage

There are three ways to create an object

GetSharedPreferences () of Context ()

GetPreferences () of the Activity ()

Getdefasharsharedpreferences () of PreferenceManager ()

Get Data

SharedPrefs. getXXX () method, such as getInt () and getString ()

Store data to obtain the Editor object sharedPrefs. edit ();

The editor. putXXX () method for storing data, such as putInt () and putString ()

Submit the data editor. commit () to save ()

We can find a file through the path to see the running result path. I have mentioned above that I am using Genymotion testing.

The root permission is required to access the internal storage of the mobile phone.

 

 

 

 

 

 

 

Internal Storage

Saves data in the memory space, where users cannot easily access the data. root permission is required to access the data. Stored in the/data/package name/files Folder

Usage

It still needs to operate the File through FileInputStream and FileOutputStream, but not through their construction methods.

Get FileInputStream

FileInputStream FCM = openFileInput (); (Activity method)

FileOuputStream fos = openFileOutput (); (Activity method)

File will be automatically created

 

External SDCard Storage

When operating the SD card, you need to add permissions to the list file.

 

Save the data to the SDCard. Any program can be accessed, and users can easily view and modify the data.

Usage

Use FileInputStream and FileOutputStream to operate the File.

SDCard operation class Environment to get the SDCard status

Environment. getExternalStorageState (); get the extended card status

Environment. MEDIA_MOUNTED installed and readable and writable

Environment. MEDIA_MOUNTED_READ_ONLY installed but read-only

Removed by Environment. MEDIA_REMOVED

Obtain common folder paths

Environment. getExternalStorageDirectory (); get the expansion card root folder

This path cannot be found under the SD card. You can only say it gently ~

 

Paste a demo

Running Effect

In edittext, enter the text, click the write button, and click "read". The important thing about textview is to add permissions three times ~ Add permission ~ Add permission ~

 

Activity_main.xml

  

<? Xml version = "1.0" encoding = "UTF-8"?> <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/plugin" android: paddingRight = "@ dimen/plugin" android: paddingTop = "@ dimen/plugin" android: orientation = "vertical" tools: context = "com. example. lesson15_data_storage.MainActivity "> <CheckBox android: id =" @ + id/push "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: text = "whether to append to the end of the original file"/> <EditText android: id = "@ + id/edit" android: layout_width = "match_parent" android: layout_height = "wrap_content"/> <TextView android: id = "@ + id/text_view" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "show text"/> <Button android: id = "@ + id/inner_storage" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "save text to internal storage" android: onClick = "onClick"/> <Button android: id = "@ + id/inner_read" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "read the text stored in the internal storage to TextView" android: onClick = "onClick"/> <Button android: id = "@ + id/outter_read" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: onClick = "onClick" android: text = "read extended card text to textview"/> <Button android: id = "@ + id/outter_write" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: onClick = "onClick" android: text = "write text to expansion card"/> </LinearLayout>

 

MainActivity

  

Public class MainActivity extends AppCompatActivity implements View. onClickListener {private CheckBox cbPush; private TextView textView; private EditText edit; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); cbPush = (CheckBox) findViewById (R. id. push); textView = (TextView) findViewById (R. id. text_view); edit = (EditText) findViewById (R. id. edit); getSharedPreferences ();}/*** stores the selected status of a CheckBox */private void getSharedPreferences () {// Context get parameter 1 file name parameter 2 File Permission SharedPreferences preferences = getSharedPreferences ("setting", Context. MODE_PRIVATE); // the file name obtained by the activity is the current activity name SharedPreferences preferences1 = getPreferences (MODE_PRIVATE); // obtain the editor object SharedPreferences. editor editor1 = preferences1.edit (); // Save the data edi Tor1.putString ("text", "Get Through activity object"); // submit data editor1.commit (); // PreferenceManager get file name automatically generate access permission default private PreferenceManager. getdefasharsharedpreferences (MainActivity. this ). edit (). putString ("text", "obtained through PreferenceManager "). commit (); // parameter 1 key parameter 2 default value basic data type requirements cannot be empty so the default value boolean checked = preferences must exist. getBoolean ("cbPush", false); cbPush. setChecked (checked); cbPush. setOnCheckedChangeListener (new Compo UndButton. onCheckedChangeListener () {@ Override public void onCheckedChanged (CompoundButton buttonView, boolean isChecked) {// obtain the access permission of parameter 2 stored in parameter 1 through context SharedPreferences sharedPreferences = getSharedPreferences ("setting", Context. MODE_PRIVATE); // gets the editor object SharedPreferences. editor edit = sharedPreferences. edit (); // Save the data to edit. putBoolean ("cbPush", isChecked); // submit the modification. commit () ;}}) ;}@ Overri De public void onClick (View v) {switch (v. getId () {case R. id. inner_storage: write (); // write to the internal file Toast. makeText (MainActivity. this, "written successfully", Toast. LENGTH_SHORT ). show (); break; case R. id. inner_read: read (); // read the internal file Toast. makeText (MainActivity. this, "read successful", Toast. LENGTH_SHORT ). show (); break; case R. id. outter_read: oread (); // read the SDK file Toast. makeText (MainActivity. this, "read successful", Toast. LENGTH_SHORT ). show (); brea K; case R. id. outter_write: owrite (); // write the SDK file Toast. makeText (MainActivity. this, "written successfully", Toast. LENGTH_SHORT ). show (); break ;}} private void oread () {String state = Environment. getExternalStorageState (); try {// judge whether read/write or read-only if (state. equals (Environment. MEDIA_MOUNTED) | state. equals (Environment. MEDIA_MOUNTED_READ_ONLY) {File sdcardRoot = Environment. getExternalStorageDirectory (); File read = new File (sdca RdRoot, "my/text.txt"); if (read. exists () {FileInputStream FCM = new FileInputStream (read); // bytes are converted to Byte encoding. new InputStreamReader (FCM, "UTF-8 ") android default UTF-8 BufferedReader reader = new BufferedReader (new InputStreamReader (FCM); String str = reader. readLine (); textView. setText (str); reader. close (); FCM. close () ;}} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. pr IntStackTrace () ;}} private void owrite () {try {// get extended card status String state = Environment. getExternalStorageState (); // whether to read or write if (state. equals (Environment. MEDIA_MOUNTED) {// get the extended card folder directory File sdcardRoot = Environment. getExternalStorageDirectory (); File save = new File (sdcardRoot, "my/text.txt"); // determine whether the object exists if (save. exists () {} else {// determine whether the parent folder exists if (! Save. getParentFile (). exists () {// create a folder save. getParentFile (). mkdirs ();} // create a File save. createNewFile ();} String text = edit. getText (). toString (); // whether to append cbPush to the end of the original file. isChecked () checkbox whether to select FileOutputStream fos = new FileOutputStream (save, cbPush. isChecked (); fos. write (text. getBytes ("UTF-8"); fos. flush (); fos. close (); // whether it is a folder // save. isDirectory (); // whether it is a file // save. isFile (); // whether the file name is hidden. starting File // save. isHidden (); // get the object name array of all sub-files // save. list (); // get the array of all sub-files // save. listFiles () ;}} catch (IOException e) {e. printStackTrace () ;}} private void read () {try {// read the written file FileInputStream FCM = openFileInput ("text.txt"); int len =-1; byte [] B = new byte [1024]; ByteArrayOutputStream bos = new ByteArrayOutputStream (); while (len = Fi. read (B ))! =-1) {bos. write (B, 0, len);} textView. setText (bos. toString ("UTF-8"); bos. close (); FCM. close ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}} private void write () {try {// get the content of the input box String text = edit. getText (). toString (); // determines whether it is null if (TextUtils. isEmpty (text) return; // write method append or overwrite int mode = cbPush. isChecked ()? MODE_APPEND: MODE_PRIVATE; // obtain FileOutputStream fos = openFileOutput ("text.txt", mode); // convert the string to byte and write the file fos. write (text. getBytes ("UTF-8"); fos. flush (); fos. close ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.