. Net Code agricultural Android --- quick introduction to data storage, agricultural android ---
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, which cannot be replaced by each other. Please refer:
Method 1: Shared Preferences
You can call it a user preference parameter. As the name suggests, it is used to store user-defined settings or other "micro" user data.
Wait. It seems that I forgot one thing. It's very important. It's very important! Follow the instructions below:
If you often view files, you will surely find such a strange phenomenon.
The files in these three paths are exactly the same!
Actually, this is the truth.
This concept must be clear, and then return 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 can be divided into two types:
Stored to the default system location
First look at the code
/* Name file name, only name, does not contain 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 }}
Pay attention to the comments in the Code. After the file name is specified, it will be stored in the previous/data/<package name>/files/<name> by default. The default format is xml, k/v format.
Store to custom location
public void saveToSdcard(String filename,String content) throws Exception{ File file=new File("/storage/sdcard0",filename); FileOutputStream outputStream=new FileOutputStream(file); outputStream.write(content.getBytes()); outputStream.close(); }
You can specify the file location, which is flexible. However, it is recommended that you follow the Android conventions to use the default storage location for ease of management and maintenance and clear structure.
Method 3: SqlLite database storage
For SqlLite introduction, please use this channel. SqlLite is embedded in Android, so you do not need to install the database or anything during deployment.
The SqlLite scenario is suitable for storing large and complex data and related guis.
First look at the code segment:
Public class DbOpenHeler extends SQLiteOpenHelper {// 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) {// when the first creation is performed, 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 ");}}
Do you see OnCreate and OnUpgrade? 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 ().
Detailed SqlLite operation instance, please see http://www.cnblogs.com/cczw/archive/2012/05/23/2514544.html
Method 4: ContentProvider
This 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 verified for many operations. Files in the path in method 1 areBy default, only access requests that are supposed to be accessed are allowed,(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
Concept 1. Uri (Uniform Resource Identifier)
Name each resource of the system, for example, call records.
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, and D:
A: The standard prefix. 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 name of The. class that defines the ContentProvider package; "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, the data corresponding to the id is returned. If no ID exists, all is returned. "content: // hx. android. text. myprovider/tablename/# "# indicates the data id
Concept. 2. 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, you need to match all the Uri paths to the registration, 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.
• The parseId (uri) method is used to obtain the ID part from the path.
ContentResolver: When an external application needs to add, delete, modify, and query data in ContentProvider, you can use the ContentResolver class 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:
Step 1: Define your Provider class
Public class MyContentProvider extends ContentProvider {private DbOpenHeler dbOpenHeler; // previous SqlLite helper class}
Step 2: Define your Uri
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 values: INSERT (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. personprovider "," person/# ", Integer. parseInt (PERSON. DELETE. toString ()));}
Step 3: declare in AndroidManifest. xml
<provider android:name=".MyContentProvider" android:authorities="com.letchoice.providers.personprovider" > </provider>
Step 4: implement the CURD method (only one query is attached)
@ Override public Cursor query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder) {// TODO Auto-generated method 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 = Conten is queried. TUris. 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 );}}
Step 5: Call query externally to obtain the expected results.
Public void testQuery () {Uri uri = Uri. parse ("content: // com. letchoice. providers. personprovider/person "); ContentResolver resolver = this. getContext (). getContentResolver (); // 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 ();}
Method 5: Network Access
The above several types of storage are stored on local devices. In addition, there is also a way to store (obtain) data and store and obtain data 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.
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; impor T 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 parameter try {// set the parameter encoding request. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8); // send the request and obtain the feedback. HttpResponse httpResponse = new Defa Ulthttpclient(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 ();}}}
Do not forget to set the network access permission in the configuration file: <uses-permission android: name = "android. permission. INTERNET"/>
For more information, see:
Http://www.cnblogs.com/chenglong/articles/1892029.html
Http://blog.sina.com.cn/s/blog_5688414b0100xagp.html
Http://www.cnblogs.com/hanyonglu/archive/2012/03/01/2374894.html
Net website and android how to transmit data
Create a webservice and call the webservice method in android.
How does android access the pc-side database through wifi and save the data in sqlite?
Android ---- web pages (interfaces provided by JSP. net php and so on) ---- for database Android, you only need to access the webpage to trigger parameters .. IIS and tomcat will always be on the server