Data storage for Android Development (I): android Data Storage

Source: Internet
Author: User

Data storage for Android Development (I): android Data Storage

Data Storage Method for Android development (1)

I have been developing Android in Xiamen for two months. It's almost valentine's day, and I am still working on code. Develop your own APP on the platform and use the knowledge of data storage. Here we will summarize:

Generally, there are three data storage methods:One is a file, the other is a database, and the other is a network.Among them, files and databases may be used a little more, files are more convenient to use, and programs can define their own formats; databases may be slightly difficult to use, but it has its advantages, for example, in the case of massive data volumes, the performance is superior, with query functions, encryption, locks, cross-application, and cross-platform functions. networks are used for important tasks, such as scientific research and exploration, real-time data collected by airlines needs to be immediately transmitted to the data processing center through the network for storage and processing.

For the Android platform, its storage methods are similar to these. They are classified as files, databases, and networks in general. But from the developer's point of view, it can be divided into the following five methods:
1. SharedPreferences sharing preferences
2. Internal Storage space
3. External Storage
4. SQLite Database
5. Internet Network
These methods have their own advantages and disadvantages. They should be selected based on different actual conditions, but they cannot provide unified standards. The following describes their advantages and disadvantages and the most appropriate use cases in various ways:

The following is a test based on your own development. A simple APP is used to help the Group understand Android Data Storage:

(1) files

In fact, this APP is also downloaded online.


Function: download an image from the network to your collection.

Paste the code: 1. MainActivity. java

Package com. test. learning;
Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. InputStream;
Import java.net. HttpURLConnection;
Import java.net. MalformedURLException;
Import java.net. URL;
Import android. app. Activity;
Import android. OS. Bundle;
Import android. OS. Handler;
Import android. OS. Message;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Import android. widget. EditText;
Import android. widget. Toast;


Public class MainActivity extends Activity implements Runnable {
Private EditText urlText;
Private Button button;
Private Handler handler; // declare a Handler object
Private boolean flag = false;


@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
UrlText = (EditText) findViewById (R. id. editText_url );
Button = (Button) findViewById (R. id. button_go );
Button. setOnClickListener (new OnClickListener (){


@ Override
Public void onClick (View v ){
Thread t = new Thread (CopyOfMainActivity. this );
T. start (); // enable the thread
Handler = new Handler (){
@ Override
Public void handleMessage (Message msg ){
If (flag ){
Toast. makeText (CopyOfMainActivity. this, "the file has been downloaded! ",
Toast. LENGTH_SHORT). show ();
} Else {
Toast. makeText (CopyOfMainActivity. this, "An error occurred while downloading the file! ",
Toast. LENGTH_SHORT). show ();
}
Super. handleMessage (msg );
}
};
}
});
}


@ Override
Public void run (){
Try {
String sourceUrl = urlText. getText (). toString ();
URL url = new URL (sourceUrl );
HttpURLConnection urlConn = (HttpURLConnection) url
. OpenConnection ();
InputStream is = urlConn. getInputStream (); // gets the input stream object
If (is! = Null ){
String expandName = sourceUrl. substring (
SourceUrl. lastIndexOf (".") + 1, sourceUrl. length ())
. ToLowerCase ();
String fileName = sourceUrl. substring (
SourceUrl. lastIndexOf ("/") + 1,
SourceUrl. lastIndexOf ("."));
File file = new File ("/sdcard/pictures/" + fileName + "."
+ ExpandName );
FileOutputStream fos = new FileOutputStream (file );
Byte buf [] = new byte [128];
While (true ){
Int numread = is. read (buf );
If (numread <= 0 ){
Break;
} Else {
Fos. write (buf, 0, numread );
}
}
}
Is. close (); // close the input stream object
UrlConn. disconnect ();
Flag = true;
} Catch (MalformedURLException e ){
E. printStackTrace ();
Flag = false;
} Catch (IOException e ){
E. printStackTrace ();
Flag = false;
}
Message m = handler. obtainMessage (); // get a Message
Handler. sendMessage (m); // send a message
}
}

2. main. xml Code

<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "horizontal"
Android: background = "@ drawable/background"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent">
<EditText
Android: layout_weight = "1"
Android: id = "@ + id/editText_url"
Android: layout_height = "wrap_content"
Android: layout_width = "0dp"
Android: text = "@ string/defaultvalue"
Android: lines = "1"/>
<Button
Android: id = "@ + id/button_go"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "@ string/go"/>
 
</LinearLayout>

3. string. xml Code

<? Xml version = "1.0" encoding = "UTF-8"?>
<Resources>


<String name = "hello"> Hello World, MainActivity! </String>
<String name = "app_name"> 14.5 </string>
<String name = "go"> download </string>
<String name = "defaultvalue"> http://p8.qhimg.com/dm/620_270_/t011685779b50979038.jpg </string>
</Resources>

Run the command to obtain the figure above.


Data storage problems in Android Development

First of all, let me talk about it more. Let's take two steps first.
1. Network Access
2. Data Storage
I. Android Network Access is generally an imitation of the Http protocol. Simply put, it is the application of the HttpGet class and the HttpPost class. Then you give the address to it, and the http protocol will return a response, this response includes the return code and content, and the content you want is included in the returned content. So here is your first question: file or data? What is actually returned depends on what the server interface returns to you. Generally, an enterprise returns a string data in xml format or a string data in Json format, the content of your questions will be included in this article. Another possibility is that you initially accessed not a server interface, but a network file address. If so, if you want to obtain it, you need to use the JAVA input/output stream technology to read and write files on the network. Then, it is a file.
II. Data Storage
There are a total of five types of data storage for android. You can check them for details, but here I will mention that if you want to close the data, you should create a database, then insert the data into the database. If it is a file, you need to convert the binary data and store it again, so that it becomes confidential. If you want to put the data in your mobile phone card, so we need to have the first permission here, because you are a process from scratch, you have to create it without this file, and then write the file data to the file using the JAVA input/output stream technology, after the storage is complete or after writing, the entire operation is complete.
Please cherish it and contact me again if you do not understand it.

Android Data Storage Methods

Generally, there are three Data Storage Methods: file, database, and network. Among them, files and databases may be used a little more, files are more convenient to use, and programs can define their own formats; databases may be slightly difficult to use, but it has its advantages, for example, in the case of massive data volumes, the performance is superior, with query functions, encryption, locks, cross-application, and cross-platform functions. networks are used for important tasks, such as scientific research and exploration, real-time data collected by airlines needs to be immediately transmitted to the data processing center through the network for storage and processing. For the Android platform, its storage methods are similar to these. They are classified as files, databases, and networks in general. But from the developer's point of view, it can be divided into the following five methods: 1. sharedPreferences sharing preferences 2. internal Storage space 3. external Storage space 4. SQLite Database 5. internet network methods have their own advantages and disadvantages. They should be selected based on different actual conditions, but they cannot provide unified standards. The following describes the advantages and disadvantages of these methods and the most suitable use cases: 1. shared Preferences SharedPreferences are used to store basic pairs of Key-Value pairs. Note that they can only store basic data types, that is, int, long, boolean, String, float. In fact, it is equivalent to a HashMap. The only difference is that the Value in HashMap can be any object, while the Value in SharedPreferences can only store the basic data type (primitive types ). For how to use it, refer to the Android Developer Guide, which is unique here. In this case, the best choice for SharedPreferences is to save configuration information, because many configuration information is Key/Value. In fact, in Android, SharedPreferences are used most often to save the Settings information. In the system Settings, the Settings in various applications are also used. In addition, for the convenience of saving configuration information using SharedPreferences in Android, PreferenceActivity is used for encapsulation. That is to say, if you want to create Settings in the application, you can directly use PreferenceActivity and some related components specially encapsulated for Preference, instead of directly creating them, read and save SharedPreference. These components in the Framework will do these tasks for you. Let's talk about some tips when using SharedPreference. It can only save basic data types, but what if I want to save an array? You can process the data, convert it into a String, and restore the data when it is retrieved. For example, if you want to save an object, what should you do, you can serialize an Object into a character sequence or convert it to a String (Object. toString (), or set its HashCode (Object. hashCode () is saved as Value. In short, SharedPreferences is very convenient to use and can be flexibly applied. Because it is simple and convenient, try not to use files or databases if you can use it. 1. Internal Storage refers to the so-called Internal Storage and external Storage, which refer to whether the mobile phone is built in. The built-in storage space of the mobile phone is called internal storage. It cannot be changed once the mobile phone leaves the factory. It is also one of the hardware indicators of the mobile phone, generally, the larger the phone storage space, the more expensive the mobile phone will be. (in many places, it is called the mobile phone memory, but we know that this is not accurate when we do software, memory refers to the storage program, Data ...... remaining full text>

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.