Asynchronous parsing AsyncTask tool class encapsulation in Android

In order to make it more convenient for us to operate the UI in the child thread, Android also provides some other useful
tools , AsyncTask is one of them. With AsyncTask, you
can switch from child thread to main thread very easily, even if you don't know anything about the asynchronous message processing mechanism. Of course, the implementation principle behind AsyncTask is also based on the asynchronous
message processing mechanism, but Android has done a good encapsulation for us; the
AsyncTask class is an abstract class that specifies three generic parameters. The purpose of these three parameters:
1. Params
The parameters that need to be passed in when executing AsyncTask can be used in background tasks.
2. When the Progress
background task is executed, if the current progress needs to be displayed on the interface, the generic type specified here is used as the progress unit.
3.Result
After the task is executed, if the result needs to be returned, use the generic type specified here as the return value type.
Therefore, a simplest custom AsyncTask can be written as follows:
class DownloadTask extends AsyncTask<Void, Integer, Boolean> {
...
}
After learning HttpURLConnection, you need to use asynchronous loading every time you initiate a request, because network requests must be placed Executed in child threads, an application is likely to use network functions in many places, and the code only has different paths for network requests. Therefore; we can extract asynchronous loading and initiating network requests into a common class library, This class does not process images, but only returns a URL to a json string processing class;
1; A tool class that converts the flow to a string
package com.example.asynnet.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ReadStreamUtils {
	public static String toJson(InputStream is) {
		byte[] b = new byte[1024];
		int len ​​= 0;
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			while ((len = is.read(b)) != -1) {
				os.write(b, 0, len);
				os.flush();
			}
			return os.toString("utf-8");
		} catch (IOException e) {
			e.printStackTrace ();
		} finally {
			try {
				if (os != null)
					os.close();
			} catch (IOException e) {
				e.printStackTrace ();
			}
		}

		return null;
	}

}


2; AsynTask tool class extraction
package com.example.asynnet.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.AsyncTask;

public class UrlFileAsynNetUtils extends AsyncTask<String, Void, String> {

	@Override
	protected String doInBackground(String... params) {
		try {
			URL url = new URL(params[0]);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setConnectTimeout(8000);
			connection.setReadTimeout(8000);
			if (connection.getResponseCode() == 200) {
				return ReadStreamUtils.toJson(connection.getInputStream());
			}
		} catch (MalformedURLException e) {
			e.printStackTrace ();
		} catch (IOException e) {
			e.printStackTrace ();
		}
		return null;
	}

}


3. You can get the json string by passing in the url in the Activity
        private ListView lv;
	private List<String> types;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView(R.layout.activity_main);
		lv = (ListView) findViewById(R.id.lv_booksort);
		String url = "http://japi.juhe.cn/comic/category?key=26e141e02d5c802d39ccf3ae918a7146";
		UrlFileAsynNetUtils netu = new UrlFileAsynNetUtils () {

			@Override
			protected void onPostExecute(String result) {
				Gson gson = new Gson ();
				BookSortJson list = gson.fromJson (result, BookSortJson.class);
				types = list.result;
				//
				lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,
						android.R.layout.simple_list_item_1,types ));
			}
		};
		// start calling
		netu.execute(url);
		
		//Click to query the list of books of the corresponding type
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent=new Intent(MainActivity.this, BookItemActivity.class);
				intent.putExtra("type", types.get(position));
				startActivity(intent);
			}
		});
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326532030&siteId=291194637