Android Network download and Data Persistence

Source: Internet
Author: User

The first three articles talk about listView and handler. Hey, I will talk about URL class and android io this time. Next, I will combine these contents, create a small instance for downloading large files from the server. What should I do ~

First, we will introduce a small tool that can simulate servers, hfs,

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/112143CS-0.png "title =" image 2.png "/>

A small server uses tomcat, but it is very small and only kb. I will append the test to my blog.

There is nothing to say about this server. The only thing to note is to write http: // 10.0.2.2 when accessing the server path in the project: 8080/path: if there is a port, you do not need to write the port number. The directory should not contain Chinese characters or special symbols. If there is a need, it will involve some browser Encoding Problems.

OK. Now let's talk about how to use the URL class...

Step 1: To use network resources, you must register permissions in the list file:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1121433244-1.png "title =" image 1.png "/>


This is the text editing mode. to read the code, add such a sentence.

<uses-permission android:name="android.permission.INTERNET"/>

Let's take a look at the consequences of not adding permissions...

The project does not report fc, but such logs are displayed in the log:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1121431526-2.jpg "title =" promiss_exception.jpg "/>

In the first sentence of the log, the error message of permission denied is written. That is to say, you do not have the permission to register...


Step 2: code:


Import java. io. IOException; import java. io. inputStream; import java.net. malformedURLException; import java.net. URL; import java.net. URLConnection; import android. OS. bundle; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. imageView; import android. Widget. textView; public class MainActivity extends Activity implements OnClickListener // The click event here is android. view. view. in the {// URL in the browser: http: // localhost: 8080/downloading in the OnClickListener package, change localhost to 10.0.2.2 private final static String URL_PATH = "http: // 10.0.2.2: 8080/test "; private final static String TEXT_PATH ="/text.txt "; private final static String IMAGE_PATH ="/img.png "; private final Static String LOCALHOST_TXT_PATH = "/test.txt"; // used in the following project... Private URL url; private URLConnection urlConn; private ImageView mImageView; private TextView mTextView; private TextView mLocalhost; // private EditText mWrite used by io code; // @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); findViewById (R. id. B _load_img ). setOnClickListener (this); findViewById (R. id. B _load_text ). SetOnClickListener (this); findViewById (R. id. B _load_localhost ). setOnClickListener (this); findViewById (R. id. B _write ). setOnClickListener (this); mWrite = (EditText) findViewById (R. id. et_write); mTextView = (TextView) findViewById (R. id. TV _show_text); mImageView = (ImageView) findViewById (R. id. img_show_loadimg); mLocalhost = (TextView) findViewById (R. id. TV _localhost) ;}@ Override public boolean onCrea TeOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}@ Override public void onClick (View v) {switch (v. getId () {case R. id. B _load_text: loadText (); // load the text break; case R. id. B _load_img: loadImg (); // load the image break; default: break;} private void loadText () // load the text {InputStream is = null; // to disable Stream file java knowledge, not much to explain... Try {url = new URL (URL_PATH + TEXT_PATH); // get URL resource throw // MalformedURLException urlConn = url. openConnection (); // get the connection and throw IOException // after obtaining the connection, an IO stream sent from the server is = urlConn. getInputStream (); // parse all input streams when they exist; StringBuilder strbuff = new StringBuilder (); // someone may ask why StringBuffer is not used here //, you can see from the source code that buffer is thread-safe. // It is completely unnecessary here, wasting resources byte [] buffer = new byte [1024]; // define a byte buffer array int len = 0; // len is used to receive The number of bytes read from is. // someone will say this is useless. Hey, if you have experience, you will know that the buffer may not be fully filled, // if it is not full, the remaining parts are assigned 0 values according to the java syntax, so when you print the read content, you will find a bunch of garbled characters. // if you don't believe it, try to remove len and scatter ~, Programming is what has grown in various experiments ~ While (-1! = (Len = is. read (buffer) {strbuff. append (new String (buffer, 0, len);} mTextView. setText (strbuff. toString ();} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {try {if (is! = Null) {is. close () ;}} catch (IOException e) {e. printStackTrace () ;}} private void loadImg () // load the image {// This is much easier than parsing the text to parse the image, android provides a Bitmap class and BitmapFactory to parse this guy // read the code: try {url = new URL (URL_PATH + IMAGE_PATH); urlConn = url. openConnection (); InputStream is = urlConn. getInputStream (); // The steps here are the same as loading text .. // Start to load the image Bitmap map = BitmapFactory. decodeStream (is); // The amount (⊙ o ⊙ )... The image is loaded. // put this guy in the UI if you don't believe it... MImageView. setImageBitmap (map); // you do not know how to set the image displayed in ImageView... // Let's say more here... // If there is a resource id, you can directly set the mImageView. setImageResource (R. drawable. ic_launcher); // There are many ways to set images in the android system, such as setImageBitmap...} Catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}

Hey, I don't know. You can't remember what I said in my third blog. Downloading resources like this is time-consuming. The drop must be executed in the Child thread... Hey, don't rush to let everyone experience the charm of ANR first.

If you are interested, you can try to see if you can solve this ANR problem.

Topic 2: Access Local Resources

In Android 4, the method for accessing local resources is described first. Many sdCard users prefer to write "/mnt/sdCard" directly when writing sdcard paths. If your project is customized, you may not be able to access the local sdcard. The correct method is as follows:

File sdCardFile = Environment. getExternalStorageDirectory (); // The obtained file is the path of the sdCard.

Let's look at the Code:

Step 1: user permissions are also required to access local resources:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Step 2: write code


Private void write () {// write local file: permission required: <uses-permission // android: name = "android. permission. WRITE_EXTERNAL_STORAGE "/> File sdCardFile = Environment. getExternalStorageDirectory (); // The directory path of the sdcard is String path = sdCardFile. getAbsolutePath () + LOCALHOST_TXT_PATH; // construct the complete path FileOutputStream fos = null; try {String str = mWrite. getText (). toString (); // obtain the input value fos = new FileOutputStream (path); fos from the component. wri Te (str. getBytes (); // write text} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} finally {try {if (fos! = Null) fos. close ();} catch (IOException e) {e. printStackTrace () ;}} private void localhost () {// read the local file. permission required: <uses-permission // android: name = "android. permission. WRITE_EXTERNAL_STORAGE "/> // In fact, this method is similar to obtaining resources from the network... Only the information sources are different ~~~ File sdCardFile = Environment. getExternalStorageDirectory (); // The directory path of the sdcard is String path = sdCardFile. getAbsolutePath () + LOCALHOST_TXT_PATH; // construct the complete path FileInputStream FCM = null; try {FD = new FileInputStream (path); StringBuilder strBuff = new StringBuilder (); byte [] buffer = new byte [1024]; int len = 0; while (-1! = (Len = Fi. read (buffer) {strBuff. append (new String (buffer, 0, len);} mLocalhost. setText (strBuff. toString ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}


I have written these two codes in the URL project, so that you don't have to worry about so many projects... Right? O (∩ _ ∩) O ~



This article is from the "android_home" blog, please be sure to keep this http://yangzheng0809.blog.51cto.com/6024606/1273039

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.