Android Development notes how data is stored in Android (i) _android

Source: Internet
Author: User
Tags gettext sqlite sqlite database


For the development platform, if the data storage has good support, then the development of the application will have a great role in promoting.



In general, there are three ways to store data: One is a file, one is a database, and the other is a network. Where files and databases may be used a little more, the file is easy to use, the program can define its own format; The database used a bit annoying lock some, but it has its advantages, such as in the massive data performance is superior, there is query function, you can encrypt, can add locks, across applications, cross-platform and so on; For the more important things, such as scientific research, exploration, aviation and other real-time data collection needs to be transmitted to the data processing center for storage and processing, real-time needs.



For the Android platform, it's stored in the same way, by the way the overall score, but also files, databases and networks. But I think it can be subdivided into the following five ways from the storage object:



1.1 Way



1.Shared Preferences: System configuration information that is primarily used to save programs. Used to store "Key-values paires". Typically used to save information that was set when the program was started, so that the information that was previously set will continue to be retained the next time the program starts.
2.xml: Save complex data, such as SMS Backup.



3.Files: Save the information in the form of a file. You can get or save related information by reading and writing to the file.



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



5.NetWork: Save the data on the network.



1.2 Differences



  1. Shared Preferences:



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



Sharedpreferences is automatically saved as a file in XML format, and is expanded to/data/data/<packagename>/shared_prefs under Ddms in the Files Explorer. Take your own project as an example, you can see a file called Setting_infos.xml



2. Files



In Android, it provides the Openfileinput and Openfileouput methods to read files on the device, look at the example code below, as shown below:


String file_name = "Tempfile.tmp"; Determine the filename to manipulate the file
fileoutputstream fos = openfileoutput (file_name, context.mode_private);//initialization


The two methods in the preceding code only support reading files in the application directory, and reading files that are not in their own directories will throw an exception. The caveat is that if the file you specified does not exist when you call FileOutputStream, Android automatically creates it, so you don't need to determine if the file exists. Also, by default, the original file content is overwritten when written, and if you want to attach the newly written content to the original file content, you can specify that the mode is Context.mode_append, which involves four modes of openfileoutput (). Below I will explain in detail and the case.



3. SQLite



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



  4. Network:



Upload data to the network



Add:



1.Shared preferences The underlying use of Xml,xml can also save data, but Shared preferences can only save key-value pairs, XML can save complex data



2.Content provider The bottom or use the SQLite database, is also a way.



1.3 Examples



1. Shared Preferences:



Small case: User input account password, click on the login button, login while persisting to save the account number and password



Store account password with Sharedpreference



• Write data into sharedpreference


Get a Sharedpreference object
sharedpreferences sp = getsharedpreferences ("config", mode_private);
Get Editor
Editor ed = Sp.edit ();
Write Data
ed.putstring ("name", name);


Note: Here remember to put the finished, you must commit.



• Take data from sharedpreference


Sharedpreferences sp = getsharedpreferences ("config", mode_private);
Take the data from the sharedpreference.


Code



• Layout Files


<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 a user name"
/>
<EditText
android: id = "@ + id / et_pass"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: hint = "Please enter the 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 username and password"
android: layout_centerVertical = "true"
/>
<Button
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: text = "Login"
android: layout_alignParentRight = "true"
android: onClick = "login"
/>
</ RelativeLayout>
</ LinearLayout>


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);
Remove data String name = sp.getstring ("name", "") from Sharedpreferences;
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);
Deposit data into sharedpreferences Editor ed = Sp.edit ();
Ed.putstring ("name", name);
Ed.putstring ("Pass", pass);
Submit Ed.commit ();  }
}


2. Files



Small case: User input account password, tick "Remember account password", click on the login button, login and persistent save account and password



• Read and write files (RAM) in the internal storage space



• Layout file: Same layout as above



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 the SharedPreferences object
SharedPreferences sp = getSharedPreferences ("info", MODE_PRIVATE);
// Retrieve data from SharedPreferences
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 the SharedPreferences object
SharedPreferences sp = getSharedPreferences ("info", MODE_PRIVATE);
// Save the data in SharedPreferences
Editor ed = sp.edit ();
ed.putString ("name", name);
ed.putString ("pass", pass);
//submit
ed.commit ();
}
}

• Read and write files in external storage space (SD card)



• Layout file: Same layout as above



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 ()) {//Detect whether the SD card is currently available if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {//
File File = new file ("Sdcard/info.txt");
Returns a file object that contains the path to the real path of the SD card, file = new file (Environment.getexternalstoragedirectory (), "info.txt"); try {fileoutputstream fos = new FileOutputStream (file); Fos.write ((Name + "# #" + Pass). GetBytes ()); Fos.close (); (Exception e)
{//TODO auto-generated catch block E.printstacktrace ();}
else{Toast.maketext (this, "SD card not available yo Pro", 0). Show ();}
Pop-up prompt box prompts the user to login successfully toast.maketext (this, "login successful", 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 flow to character stream BufferedReader br = new Bufferedrea
Der (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:



//This API will write files to the data/data/com.itheima.permission/files/folder
FileOutputStream fos = openfileoutput ("Info1.txt", mode_private);
//This API will read the file to the Data/data/com.itheima.permission/files/folder
FileOutputStream fos = openfileoutput ("Info1.txt", mode_private);



• So, later with the Android with the API. You can look at a small example of the following openfileoutput four modes:



Four modes of Openfileoutput


mode_private = 0:-rw-rw----
mode_append = 32768:-rw-rw----
modeworldreadable = 1:-rw-rw-r--
mo deworldwriteable = 2:-rw-rw--w-


Context.mode_private: For the default mode of operation, which means that the file is private data and can only be accessed by the application itself, in which the written content overwrites the contents of the original file, and if you want to append the newly written content to the original file, you can use the Context.mode_ APPEND.



Context.mode_append: Mode checks whether the file exists, appends to the file, or creates a new file.
Context.mode_world_readable and context.mode_world_writeable are used to control whether other applications have permission to read and write to the file.
Mode_world_readable: Indicates that the current file can be read by another application; Mode_world_writeable: Indicates that the current file can be written by another application.



Note



• In Android, each application is an independent user
drwxrwxrwx
• 1th Digit: D represents a folder,-represents a file
• 第2-4位: Rwx, which indicates that the owner user (owner) of this file has permissions on the file R.: Read
W: Write
x: Executive
• 第5-7位: Rwx, which represents the permissions of users (Grouper) who are in the same group as the owner user of the file
• 第8-10位: Rwx, which represents the permissions of other user groups (other) on the file



• 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 file 1"
android: onClick = "click1"
/>
<Button
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: text = "Create file 2"
android: onClick = "click2"
/>
<Button
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: text = "Create file 3"
android: onClick = "click3"
/>
</ LinearLayout>


• 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 will write the file to the Data/data/com.bokeyuan.permission/files/folder under try {fileoutputstream fos =
Openfileoutput ("Info1.txt", mode_private);
Fos.write ("This file is private data and can only be accessed by itself". GetBytes ());
Fos.close ();
catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();}} The public void Click2 (View v) {//This API writes the file to the Data/data/com.bokeyuan.permission/files/folder under 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 ();}} The public void Click3 (View v) {//This API writes the file to the Data/data/com.bokeyuan.permission/files/folder under 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 ();}}  }


• Get SD card remaining capacity:



• Sometimes when reading and writing files, you need to determine the remaining capacity of the SD card, and then write the operation. Here's a small example of the Android system's underlying API to get the remaining capacity of the SD card.



• Layout file:


<relativelayout 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 ">
<textview
android:id=" @+id/tv "
android:layout_width=" Wrap_content " android:layout_height= "Wrap_content"
android:text= "@string/hello_world"/>


Java code:


package com.bokeyuan.getsdavail;
import java.io.File;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.app.Activity;
import android.text.format.Formatter;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
File path = Environment.getExternalStorageDirectory ();
StatFs stat = new StatFs (path.getPath ());
long blockSize;
long totalBlocks;
long availableBlocks;
// Check the current version number of the system
if (Build.VERSION.SDK_INT> = Build.VERSION_CODES.JELLY_BEAN_MR2) {
blockSize = stat.getBlockSizeLong ();
totalBlocks = stat.getBlockCountLong ();
availableBlocks = stat.getAvailableBlocksLong ();
}
else {
blockSize = stat.getBlockSize ();
totalBlocks = stat.getBlockCount ();
availableBlocks = stat.getAvailableBlocks ();
}
TextView tv = (TextView) findViewById (R.id.tv);
tv.setText (formatSize (availableBlocks * blockSize));
}
private String formatSize (long size) {
return Formatter.formatFileSize (this, size);
}
} 


The above is described in the Android development notes on the Android data storage mode (i) of the knowledge, I hope this article to share can help everyone. The next article is about how to store data in Android for Android Development notes (b), and interested friends click for more details.


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.