. Net code agriculture Android-quick introduction to Data Storage
The data storage in Andoid is different from what we usually see, or the storage of mobile devices is different from that in peacetime. There are five storage methods in Andoid. The reason is that we often use them in subsequent development. The importance is self-evident. Various storage methods make us more flexible in our selection, however, each method has its own application scenario and cannot be replaced by each other. See Method 1: Shared Preferences. You can call it a user preference parameter, as the name suggests, it is used to store some user-defined settings, or other "micro" user data. It seems that I forgot one thing. It is very important and important! Follow the instructions below: Open the R. E manager with your Android phone (what? No, but I am not sure about it.) If you often view files, you will surely find that the files in these three paths are exactly the same! In fact, the truth is that this concept must be clear, and then return to the root directory, in/data/<package name> /... in the/lib,/shared_prefs,/files, and other folders. The files stored in the sharedPreferencesfan mode are stored in/shared_prefs, you can find the Read and Write examples by yourself! The folders mentioned here are frequently used. You must be familiar with them! Method 2: file storage the file storage here can be divided into two types of storage to the system default location first look at the code copy code/* name file name, only the name, does not contain the path, such as love/* content public void save (String name, String content) {try {FileOutputStream outputStream = context. openFileOutput (name, Context. MODE_WORLD_WRITEABLE + Context. MODE_WORLD_READABLE); outputStream. write (content. getBytes (); outputStream. close ();} catch (Exception e) {// TODO: handle exception} copy the code. Note that after the file name is specified Stored in/data/<package name>/files/<name>. The default format is xml, Which is k/v. Copy the code public void saveToSdcard (String filename, String content) throws Exception {File file File = new File ("/storage/sdcard0", filename) stored in a custom location ); fileOutputStream outputStream = new FileOutputStream (file); outputStream. write (content. getBytes (); outputStream. close () ;}copy the code to specify the file location, which is flexible. However, we recommend that you follow the Android conventions, that is, use the default storage location for ease of management and maintenance, and the structure is clear. Method 3: SqlLite database storage SqlLite introduction. Please use this channel. SqlLite is embedded in Android, so you do not need to install any database during deployment. The SqlLite scenario is suitable for storing large and complex data and related guis. First read the code: copy the code public class DbOpenHeler extends SQLiteOpenHelper {// you need to manually implement the constructor public DbOpenHeler (Context contet) {super (contet, "itcast. db ", null, 3); // input version number} public DbOpenHeler (Context context, String name, CursorFactory factory, int version) {super (context," itcast. db ", null, 1); // TODO Auto-generated constructor stub} @ Override public void onCreate (SQLiteDatabase db) {// The first creation will execute // TODO Auto-generated method stub db.exe cSQL ("create table person (personId integer primary key autoincrement, name varchar (20)") ;}@ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stub // when the version number is different, the system will execute // db.exe cSQL ("alter table person ADD phone varchar (20) null") during the upgrade "); db.exe cSQL ("alter table person ADD amount integer");} copy the code to see OnCreate and OnUp Grade? These two methods must be implemented. OnCreate () is called when you initialize your custom database. You must specify a version number to identify it. OnUpgrade (): When we need to modify or upgrade the database as needed, we only need to re-write a new version number in the constructor (different from the previous version number ), the system will detect the differences and call OnUpgrade (). You only need to add the ones you want to change to OnUpgrade () and then OK the specific SqlLite operation instance. Please refer http://www.cnblogs.com/cczw/archive/2012/05/23/2514544.html Method 4: ContentProvider is a storage method for shared data. This is used when some of your data needs to be exposed to other callers. Some may say that I can put the data in a file. For example, can I access the data in a path in method 1? No. Android attaches great importance to user security. Therefore, permissions are added to many operations. Files in the path in method 1 are accessible only by default, (Public write permission is used for access), and data sharing between applications is also unified. In addition, Android provides default ContentProvider (including audio, video, image, and address book) for common data ). First, let's clarify several concepts. 1. Uri (unified resource identifier) gives a name for each resource in the system, for example, call record. 1. Each ContentProvider has a public URI, which indicates the data provided by this ContentProvider. 2. The ContentProvider provided by Android is stored in the android. provider package. Divide it into four parts: A, B, C, D. A: Standard prefix. It means that A Content Provider can control the data and cannot be changed. "content: // "B: URI identifier, which defines which Content Provider provides the data. For third-party applications, to ensure the uniqueness of the URI identifier, it must be a complete, lowercase class name. This identifier is described in the authorities attribute of the element: it is generally the package that defines the ContentProvider. class Name; "content: // com. android. text. myprovider "C: path. Generally speaking, it is the name of the table in the database you want to operate on, or you can define it yourself. Remember to keep it consistent when using it." content: // com. android. text. myprovider/tablename "D: parameter. If the URI contains the ID of the record to be retrieved, data corresponding to the id is returned. If no ID exists, all records are returned; "content: // hx. android. text. myprovider/tablename/# "# indicates the concept of data id. uriMatcher, ContentUrist, and ContentResolver because Uri represents the data to be operated, we often need to parse the Uri and obtain data from the Uri. The Android system provides two tool classes for Uri operations: UriMatcher and ContentUris. UriMatcher: Used to match a Uri. Its usage is as follows: 1. first, register all the Uri paths you need to match, as shown below: // constant UriMatcher. NO_MATCH indicates the return code (-1) that does not match any path ). UriMatcher uriMatcher = new UriMatcher (UriMatcher. NO_MATCH); // If the match () method matches content: // com. letchoice. providers. personprovider path, returns a matching Code of 1 uriMatcher. addURI ("com. letchoice. providers. personprovider "," person ", 1); // Add the uri to be matched. If the uri matches, a matching code is returned. // If the match () method matches content: // com. letchoice. provider. personprovider/person/230 path, returns a matching code of 2 uriMatcher. addURI ("com. letchoice. providers. personprovider "," person/# ", 2); // # It is a wildcard 2. after registering the Uri to be matched, you can use uriMatcher. the match (uri) method matches the input Uri. If it matches, the matching code is returned. The matching code is the third parameter passed in by calling the addURI () method. Assume that it matches the content: // com. letchoice. provider. personprovider/person path. The returned matching code is 1. ContentUris: used to obtain the ID part after the Uri path. It has two practical methods: • withAppendedId (uri, id) is used to add the ID part to the path • parseId (uri) the ContentResolver method is used to obtain the ID part from the path. When an external application needs to add, delete, modify, and query the data in ContentProvider, The ContentResolver class can be used to complete the operation, to obtain the ContentResolver object, you can use the getContentResolver () method provided by Activity. ContentResolver uses insert, delete, update, and query methods to operate data. Next let's take an example: Step1: Define your Provider class public class MyContentProvider extends ContentProvider {private DbOpenHeler dbOpenHeler; // The previous SqlLite helper class} Step2: define your Uri copy code private DbOpenHeler dbOpenHeler; private static final UriMatcher MATCHER = new UriMatcher (UriMatcher. NO_MATCH); // define a Matcher // private static final int PERSON = 1; // private static final int PERSON = 2; public enum PERSON {// custom enumeration parameter value INS ERT (1), DELETE (2); private int nCode; private PERSON (int nCode) {this. nCode = nCode;} @ Override public String toString () {// TODO Auto-generated method stub return String. valueOf (this. nCode) ;}}; // The Uri you defined here. There are two types: one with no parameters and the other with the parameter static {MATCHER. addURI ("com. letchoice. providers. personprovider "," person ", Integer. parseInt (PERSON. INSERT. toString (); MATCHER. addURI ("com. letchoice. providers. personprovi Der "," person/# ", Integer. parseInt (PERSON. DELETE. toString ();} copy the code Step 3: In AndroidManifest. <provider android: name = ". myContentProvider "android: authorities =" com. letchoice. providers. personprovider "> </provider> Step 4: implement the CURD method (only paste one query) and copy the code @ Override public Cursor query (Uri uri, String [] projection, String selection, string [] selectionArgs, String sortOrder) {// TODO Auto-generated meth Od stub SQLiteDatabase db = dbOpenHeler. getReadableDatabase (); switch (MATCHER. match (uri) {// match detection case 1: // If uri does not contain parameters, return db is queried without parameters. query ("person", projection, selection, selectionArgs, null, null, sortOrder); case 2: // If the uri contains parameters, the long rid = ContentUris is queried. parseId (uri); String where = "personId =" + rid; if (selection! = Null &&! "". Equals (selection. trim () {where + = "and" + selection;} return db. query ("person", projection, where, selectionArgs, null, null, sortOrder); default: throw new IllegalArgumentException ("this is Unknown Uri" + uri );}} copy code Step 5: obtain the expected result by calling query externally. Copy the code public void testQuery () {Uri uri = Uri. parse ("content: // com. letchoice. providers. personprovider/person "); ContentResolver resolver = this. getContext (). g EtContentResolver (); // use ContentResolver to parse uri Cursor cursor = resolver. query (uri, null, "personId asc"); // sort cursor by personal ID upgrade. moveToFirst (); while (cursor. moveToNext () {Log. I ("testQuery", cursor. getString (cursor. getColumnIndex ("name"); // print the result} cursor. close () ;}copy code Method 5: network access several types of storage are stored on local devices. In addition, there is also a way to store (obtain) data, data is stored and obtained through the network. We can call the data returned by WebService or parse the HTTP protocol to achieve network data interaction. You must be familiar with the content of java.net. * And Android.net. The following is a weather forecast that queries the region by region name. a post request is sent to the webservicex.net site to access the WebService.webservicex.net site to provide the weather forecast query service. Copy the code package com. android. weather; import java. util. arrayList; import java. util. list; import org. apache. http. httpResponse; import org. apache. http. nameValuePair; import org. apache. http. client. entity. urlEncodedFormEntity; import org. apache. http. client. methods. httpPost; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. message. basicNameValuePair; import org. apache. http. protocol. HTTP; import org. apache. http. util. entityUtils; import android. app. activity; import android. OS. bundle; public class MyAndroidWeatherActivity extends Activity {// define the source address of the content to be obtained private static final String SERVER_URL =" http://www.webservicex.net/WeatherForecast.asmx/GetWeatherByPlaceName ";/** Called when the activity is first created. * // @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); HttpPost request = new HttpPost (SERVER_URL ); // create an Http request based on the content source address // Add a variable List <NameValuePair> params = new ArrayList <NameValuePair> (); // set a region name params. add (new BasicNameValuePair ("PlaceName", "NewYork"); // add the required tr Parameter Y {// set the parameter encoding request. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8); // send the request and obtain the feedback HttpResponse httpResponse = new defaulthttpclient(cmd.exe cute (request); // parse the returned content if (httpResponse. getStatusLine (). getStatusCode ()! = 404) {String result = EntityUtils. toString (httpResponse. getEntity (); System. out. println (result) ;}} catch (Exception e) {e. printStackTrace ();}}}