Previously introduced three kinds of data storage forms of Android system, http://www.jb51.net/article/99468.htm. Today, there are two other types of content providers and networked storage, respectively. Some people may think that the memory provider and networked storage are more inclined to manipulate the data than the data, but these two ways are really related to the data, so here is a brief description of these two forms.
Content Provider:
Content Provider, the Chinese name is a memory provider, one of the four components of Android, the provider is the interface between applications to share data, in the form of database memory, can share their own data for other applications use. The reason why you need to design a separate control to manipulate data is to implement data transfer between applications. By looking at the directory structure in DDMS, you can see that the database file is unreadable and writable for other applications, and that you need to obtain data for other applications in your daily life, especially the system's own software. For example, when you open QQ or micro-mail will be prompted to sync contact people, such as backup text, these need to access and operate other applications of the database. Therefore, Google engineers in the underlying software integration of a large number of methods to take advantage of the principle of the memory provider, similar to the database to provide an external access to other applications access.
To better understand how the memory provider works, you can customize a content prompt to help understand it. First of all, write a class to inherit ContentProvider, implement the method in this class, including some additions, deletions and data initialization methods, can be implemented in the method of database additions and deletions to check operations. The database is not intended to be open to the outside, so in order to protect the data, the original return data for the method in the class is a null type. To ensure the security of the data, you can create a Urimatcher object, use the Addurif method to add the path rule of the URI, and first determine whether the incoming path conforms to the naming rule in each data operation. Use the memory provider to add the provider tag to the configuration file, specifying the hostname. A data connection can be established only if the visitor is consistent with the host name of the content provider. Implement access to the memory provider in another application. To do this: create a content provider parser that defines the path to the URI to access. The URI path has a fixed format: "content://host name/Match character". The content provider parser is used to create a link between the incremental search and the database to be manipulated. The above is often used to understand how content providers work, and there is little use of custom content prompts in actual work. The actual use of more of the content provider operating system contact, system SMS and other systems application of the database.
The content provider operating system is relatively simple to use, and most of the programs that need to be used are implemented at the bottom, to invoke various methods and related parameters. The parameters to be concerned are the URI path, the form structure of the database. You can get the appropriate parameters by looking at the underlying code. Some of the commonly used parameters can be written down for easy invocation. For example, the URI path to get all text messages is: Content://sms. The database form associated with the contact has three raw_contacts, data, and mimetypes. The URI of the Operation raw_contacts table is: Content://com.android.contacts/raw_contacts, the URI that operates the data table is: content://com.android.contacts/ Data In this paper, SMS Backup, also used to demonstrate the use of content providers to access the SMS database.
Let's take a look at the path of the database where the SMS and cell phone contacts are located. SMS in the Android simulator is stored in the path:/data/data/com.android.providers.telephony/databases/directory, contacts in the Android simulator stored in the path is:/data/ data/com.android.providers.contacts/databases/directory. For the SMS database we are concerned about the table data are: address, type, body, date, respectively, indicating the sender number, the type of text message (received or sent), SMS content, date. For the contact database three tables must be in a certain order to find the relevant data, in this do not explain. Although the development of the time does not need to understand the SMS and mobile phone contact database path, but to understand the message and mobile phone contact data is in the database, while the database is not open to the outside.
directory structure of the database related to SMS:
The case given in this paper is the backup and restore of SMS, so as to realize the operation of the System application database. First, the content provider is used to query the detailed parameters in the SMS database, and the data is stored in the XML file to the specified folder. Using XML parsing to get the data, the acquired data is in a tool class, so the data can be displayed on the interface with ListView. Concretely implemented 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 restore of SMS * Add permission to write text messages and read text messages * <uses-permission android:name= "Android.permission.READ_SMS"/> <uses-perm Ission android:name= "Android.permission.WRITE_SMS"/> * @author Huang/public class Mainactivity extends
Y {private static final String TAG = "mainactivity";
Private ListView LV; Private LIst<person> mlist;
Private Myadpter adapter;
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
LV = (ListView) Findviewbyid (r.id.lv);
Datafresh ();
//Data refresh, generally use to ListView when the best remember to refresh the data otherwise do not show public void Datafresh () {mlist = GetList ();
if (adapter = = NULL) {adapter = new Myadpter ();
}else {adapter.notifydatasetchanged (); }///ListView Display SMS Content public class Myadpter extends baseadapter{public int GetCount () {//TODO Auto
-generated Method Stub return Mlist.size ();
The public Object getitem (int position) {//TODO auto-generated The method stub is return null;
public long getitemid (int position) {//TODO auto-generated method stub return 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, NULL, NULL);
while (Cursor.movetonext ()) {String address = cursor.getstring (0);
String BODY = cursor.getstring (1);
String type = cursor.getstring (2);
String date = cursor.getstring (3);
serialization, which stores the text message as an Xml file XmlSerializer serializer = Xml.newserializer ();
File File = new file (Getfilesdir (), "Info.xml");
try {fileoutputstream fos = new FileOutputStream (file);
Serializer.setoutput (FOS, "utf-8");
Serializer.startdocument ("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);
Serializer.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 block E.printstacktrace ();
}} public void restore (view view) {Datafresh ();
Lv.setadapter (adapter);
///Using XML parsing to get SMS content private list<person> getlist () {Contentresolver resolver = Getcontentresolver (); list<person> list = new ArrayList ()//Create a person class to store the label content person p = New Person ();
File File = new file (Getfilesdir (), "Info.xml");
Xmlpullparser Pullparser = Xml.newpullparser ();
try {fileinputstream fis = new FileInputStream (file);
Pullparser.setinput (FIS, "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 block E.printstacktrace ();
return null;
}
}
}
Effect demo, my virtual machine only saved a text message:
Networked storage:
Networked storage is one of the easiest ways to understand storage. In fact, the simple point is the file upload and download. This is the form of cloud backups that are often heard. Advantages are also obvious, that is, the data stored to the server, not stored in the local, when used directly from the network to avoid the loss of information on the mobile phone and other security risks. Therefore, for this form is not a lot of explanation, directly give a file upload and download instances to demonstrate networked 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;
Accessing network operations takes time and requires adding a proxy private Handler Handler = new Handler () to the child thread () { @Override public void Handlemessage (msg) {switch (msg.what) {case Success:bitmap BM
= (Bitmap) msg.obj;
Iv.setimagebitmap (BM);
Break
Case ERORR:Toast.makeText (mainactivity.this, "Picture acquisition 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); //Upload program public void upload (view view) {//String Path = Et_path.gettext (). toString (). Trim ()//Here for the convenience of writing the path to death, this way
Less formal, generally can read Et_path to access String path = "/mnt/sdcard/info.txt";
if (textutils.isempty (path)) {Toast.maketext (this, "path cannot be empty", 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, Thro
Wable error) {//TODO auto-generated Method Stub toast.maketext (Mainactivity.this, "commit failed", 0). Show ();
}
}); }//download program public void Download (view view) {new Thread () {public void run () {try {//) is here for
Convenient to write the path to death, you can read Et_path to access, both results 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 = =) {InputStream is = Conn.getinputstream ();
Bitmap Bitmap = Bitmapfactory.decodestream (IS);
Message msg = Message.obtain ();
Msg.what = SUCCESS;
Msg.obj = bitmap;
Handler.sendmessage (msg);
Is.close ();
The catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
Message msg = Message.obtain ();
Msg.what = Erorr;
Handler.sendmessage (msg);
}
};
}.start ();
}
}
All five types of data storage are implemented. Of course, the actual development may be more complex than this, will be embedded in other knowledge points, but the data operation is undoubtedly the most basic step, is the foundation of the overall project development.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.