Five types of data storage in the Android system (II): android Data Storage

Source: Internet
Author: User

Five types of data storage in the Android system (II): android Data Storage

We have introduced three types of data storage in the Android system. Today we will introduce the other two types: content provider and network storage. Some people may think that the memory provider and network storage prefer data operations rather than data storage, but these two methods are indeed related to data, so here we will briefly describe these two forms.

Content Provider:

Content Provider. The Chinese name is the memory Provider and one of the four Android components. the Content Provider is an interface for sharing data between applications and is stored in the mobile phone memory as a database, you can share your data with other applications. A separate control needs to be designed to operate on data, in order to transfer data between applications. By viewing the directory structure in DDMS, we can see that database files are not readable and writable for other applications, and data of other applications needs to be obtained in daily life, especially the data of built-in software. For example, when you open QQ, you will be prompted whether to synchronize contacts, and when you back up text messages, you need to access and operate the databases of other applications. Therefore, Google engineers integrate a large number of methods in the underlying software to utilize the principle of memory provider, similar to providing an external access path in the database for access by other applications.

To better understand the working principle of the memory provider, you can customize a content prompt to help you understand. First, write a class that inherits ContentProvider to implement the methods in this class, including adding, deleting, modifying, querying, and initializing data. You can add, delete, modify, and query databases in the method. The database is not open to the outside, so to protect data, the original method returned data in the class is empty. To ensure data security, you can create a UriMatcher object and use the addURIf method to add Uri path rules to determine whether the entered path complies with the naming rules for each data operation. To use a memory provider, you must add the provider tag to the configuration file to specify the host name. Data connection can be established only when the visitor and the content provider have the same host name. Access the memory provider in another application. The specific operation is to create a content provider parser and define the path of the Uri to be accessed. The Uri path has a fixed format: "content: // host name/matching character ". Use the content provider parser to add, delete, modify, and query data and establish a connection with the database to be operated. The above content is usually used to understand the working principle of the content provider. In actual work, user-defined content prompts are rarely used. In practice, most of the databases used for system applications, such as content provider operating system contacts and system SMS messages.

Content provider operating system applications are relatively simple, and most of the programs that need to be used are already implemented at the underlying layer. What you need to do is to call various methods and related parameters. The parameters to be followed include the Uri path and the form structure of the database. You can view the underlying code to obtain the corresponding parameters. Some common parameters can be recorded for easy calling. For example, the Uri path for obtaining all text messages is: content: // sms. There are three contact-related database forms: raw_contacts, data, and mimetypes. The Uri for operating the raw_contacts table is: content: // com. android. contacts/raw_contacts. The Uri for operating the data table is: content: // com. android. contacts/data. This document uses text message backup and restoration to demonstrate how to use the content provider to access the text message database.

Let's take a look at the path of the database related to the text message and mobile phone contacts. The path where the text message is stored in the Android simulator is/data/com. android. providers. telephony/databases/directory. The path where the contact is stored in the Android simulator is/data/com. android. providers. contacts/databases/directory. The table data we care about in the SMS database includes address, type, body, and date, which respectively indicate the sender number, SMS type (receiving or sending), SMS content, and date. The three tables in the contact database must be searched in order to obtain the relevant data. Although you do not need to know the database path of text messages and mobile phone contacts during development, you must understand that the data of text messages and mobile phone contacts exists in the database, and the database is not open to the outside world.

Directory structure of the SMS-related database:

The case given in this article is the backup and restoration of text messages to implement operations on the system application database. First, you can use the content provider to query the detailed parameters in the text message database and store the data in the specified folder as an Xml file. Use xml to parse the data and store the obtained data in a tool class. In this way, you can use ListView to display the data on the interface. The specific implementation is as follows.

Package com. example. contentprovider; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. util. arrayList; import java. util. list; import org. xmlpull. v1.XmlPullParser; import org. xmlpull. v1.XmlSerializer; import android. app. activity; import android. content. contentResolver; import android. database. cursor; import android.net. uri; import android. OS. bundle; import android. Util. log; import android. util. xml; import android. view. view; import android. view. viewGroup; import android. widget. baseAdapter; import android. widget. listView; import android. widget. textView; import android. widget. toast;/*** backup and restoration of text messages * Add the permission to write and read text messages * <uses-permission android: name = "android. permission. READ_SMS "/> <uses-permission android: name =" android. permission. WRITE_SMS "/> * @ author Huang */public class MainActivity extends Activity {private static final String TAG = "MainActivity"; private ListView lv; private List <Person> mlist; private Myadpter adapter; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); lv = (ListView) findViewById (R. id. lv); datafresh ();} // data refresh. You 'd better remember to refresh the data when using ListView. Otherwise, public void datafresh () {m is not displayed. List = getList (); if (adapter = null) {adapter = new Myadpter ();} else {adapter. notifyDataSetChanged () ;}}// use ListView to display the text message content public class Myadpter extends BaseAdapter {public int getCount () {// TODO Auto-generated method stubreturn mlist. size ();} public Object getItem (int position) {// TODO Auto-generated method stubreturn null;} public long getItemId (int position) {// TODO Auto-generated method stubreturn 0;} public View getView (int position, View convertView, ViewGroup parent) {TextView TV = new TextView (MainActivity. this); TV. setText (mlist. get (position ). toString (); return TV ;}/// SMS backup public void bankup (View view) {ContentResolver resolver = getContentResolver (); Uri uri = Uri. parse ("content: // sms"); Cursor cursor = resolver. query (uri, new String [] {"address", "body", "type", "date"}, null ); While (cursor. moveToNext () {String address = cursor. getString (0); String body = cursor. getString (1); String type = cursor. getString (2); String date = cursor. getString (3); // serialize the text message to store XmlSerializer serializer = Xml in the form of an Xml file. newSerializer (); File file = new File (getFilesDir (), "info. xml "); try {FileOutputStream fos = new FileOutputStream (file); serializer. setOutput (fos, "UTF-8"); serializer. startDoc Ument ("UTF-8", true); serializer. startTag (null, "person"); serializer. startTag (null, "address"); serializer. text (address); serializer. endTag (null, "address"); serializer. startTag (null, "body"); serializer. text (body); serializer. endTag (null, "body"); serializer. startTag (null, "type"); serializer. text (type); serializer. endTag (null, "type"); serializer. startTag (null, "date"); serializer. text (date); se Rializer. endTag (null, "date"); serializer. endTag (null, "person"); serializer. endDocument (); fos. close (); // Toast. makeText (this, "data saved successfully", 0 ). show ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} public void restore (View view) {datafresh (); lv. setAdapter (adapter);} // get the private List of text message content through Xml parsing <Person> getList () {ContentResolver resolver = getContentResolver (); List <Person> list = new ArrayList (); // create a Person class to store the TAG content: Person p = new Person (); File file = new File (getFilesDir (), "info. xml "); XmlPullParser pullParser = Xml. newPullParser (); try {FileInputStream FCM = new FileInputStream (file); pullParser. setInput (FCM, "UTF-8"); int mtype = pullParser. getEventType (); while (mtype! = XmlPullParser. END_DOCUMENT) {String name = pullParser. getName (); switch (mtype) {case XmlPullParser. START_TAG: if ("address ". equals (name) {String address = pullParser. nextText (); p. setAddress (address);} else if ("body ". equals (name) {String body = pullParser. nextText (); p. setBody (body);} else if ("type ". equals (name) {String type = pullParser. nextText (); p. setType (type);} else if ("date ". equals (name) {String date = pullParser. nextText (); p. setDate (date);} break; case XmlPullParser. END_TAG: if ("person ". equals (name) {list. add (p) ;}break ;}mtype = pullParser. next ();} Log. I (TAG, list. toString (); return list;} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace (); return null ;}}}

In the demo, only one text message is saved in my VM:

Network Storage:

Network Storage is the easiest way to understand. In fact, it is simple to upload and download files. This is often the form of cloud backup. The advantage is also obvious, that is, data is stored on the server and not stored locally. It is directly obtained from the network when used, avoiding the loss of mobile phone information and other security risks. Therefore, there is no much explanation for this form. A file upload and download instance is provided to demonstrate network storage.

Code implementation:

Package com. example. upload; import java. io. file; import java. io. fileNotFoundException; import java. io. inputStream; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import org. apache. http. header; import com. loopj. android. http. asyncHttpClient; import com. loopj. android. http. asyncHttpResponseHandler; import com. loopj. android. http. requestParams; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. text. textUtils; import android. view. menu; import android. view. view; import android. widget. editText; import android. widget. imageView; import android. widget. toast; public class MainActivity extends Activity {protected static final int SUCCESS = 1; protected static final int ERORR = 2; private EditText et_path; private ImageView iv; // time consumed for accessing network operations, you need to add a proxy private Handler handler = new Handler () {@ Override public void handleMessage (Message msg) {switch (msg. what) {case SUCCESS: Bitmap bm = (Bitmap) msg. obj; iv. setImageBitmap (bm); break; case ERORR: Toast. makeText (MainActivity. this, "Image Retrieval failed", 0 ). show (); break;} super. handleMessage (msg) ;}}; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); et_path = (EditText) findViewById (R. id. et_path); iv = (ImageView) findViewById (R. id. iv);} // the upload program public void upload (View view) {// String path = et_path.getText (). toString (). trim (); // It is easy to write the path to death. This method is not formal and can be accessed by reading et_path.
String path = "/mnt/sdcard/info.txt"; if (TextUtils. isEmpty (path) {Toast. makeText (this, "path cannot be blank", 0 ). show (); return;} File file = new File (path); AsyncHttpClient client = new AsyncHttpClient (); RequestParams param = new RequestParams (); try {param. put ("file", file);} catch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} client. post ("http: // 192.168.1.114: 8080/", param, new AsyncHttpResponseHandler () {@ Override public void onSuccess (int statusCode, Header [] headers, byte [] responseBody) {// TODO Auto-generated method stub Toast. makeText (MainActivity. this, "submitted successfully", 0 ). show () ;}@ Override public void onFailure (int statusCode, Header [] headers, byte [] responseBody, Throwable error) {// TODO Auto-generated method stub Toast. makeText (MainActivity. this, "failed to submit", 0 ). show () ;}) ;}// download program public void download (View view) {new Thread () {public void run () {try {// you can read et_path for the convenience of writing the path here. The results are the same. URL url = new URL ("http: // 192.168.1.114: 8080/demo1.png "); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (5000); conn. setRequestMethod ("GET"); int code = conn. getResponseCode (); if (code = 200) {InputStream is = conn. getInputStream (); Bitmap bitmap = BitmapFactory. decodeStream (is); Message msg = Message. obtain (); msg. what = SUCCESS; msg. obj = bitmap; handler. sendMessage (msg); is. close () ;}} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace (); Message msg = Message. obtain (); msg. what = ERORR; handler. sendMessage (msg );}};}. start ();}}

At this point, all five types of data storage are implemented. Of course, the actual development may be more complex than this and will be embedded into other knowledge points. However, data operations are undoubtedly the most basic step and the foundation of the overall project development.

 

 

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.