android asynchronous request server data example

  • 2020-05-30 21:01:12
  • OfStack

1. In the version after android 4.0, the main thread (UI thread) does not support network request. The reason may be that the main thread is affected, which is slow and easy to get stuck, so a new thread needs to be opened to request data.


thread1 = new Thread(){
@Override
public void run() {
  try {
    URL url = new URL(WebUrlManager.CARSEVER_GetCarsServlet);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
    // The buffer to read 
    byte[] data = new byte[1024];
    int len = 0;
    String bufferString = "";
    while((len = bis.read(data)) != -1){
bufferString+=new String(data, 0, len);
    }
    carList = new JSONArray(bufferString.trim());
    //System.out.println(carList);
    /*
    for(int i=0;i

2. After the new thread is finished, 1 is started and an error is found. The null pointer nullpointerexception can only get the data after waiting for the thread to finish.

1) either determine whether the thread is still alive;

2) either set 1flag in the thread, and when finished, change its state


/*
    // Waiting for the thread thread1 completed 
    while(true){
    if(thread1.isAlive()){
try {
  Thread.sleep(500);
} catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}
    }else{
break;
    }
}
    */
    // When the thread is not finished, sleep 500 ms ms
    while(!flag){
  try {
    Thread.sleep(500);
  } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}}}

3. Process the returned json data
1) request Json data from the server and save it in carList


URL url = new URL(WebUrlManager.CARSEVER_GetCarsServlet);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
// The buffer to read 
byte[] data = new byte[1024];
int len = 0;
String bufferString = "";
while((len = bis.read(data)) != -1){
bufferString+=new String(data, 0, len);
}
carList = new JSONArray(bufferString.trim());

2) parse Json data


JSONObject car = (JSONObject) getItem(position);
try {
//this.pic.setImageBitmap(carImageArray.get(position));
this.title.setText(car.getString("title"));
this.describe.setText(car.getString("describe"));
this.updateTime.setText(car.getString("updateTime"));
this.price.setText(String.format("%.1f", car.getDouble("price"))+" wan ");
this.pic.setTag(WebUrlManager.CARSERVER_CAR_IMAGE+car.getString("image"));
new AsyncViewTask().execute(this.pic);
} catch (JSONException e1) {
e1.printStackTrace();
}

4. Image loading is usually slow, preferably asynchronous
Asynchronous request class source code


import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.ImageView;

public class AsyncViewTask extends AsyncTask {
private View mView;
private HashMap> imageCache;
public AsyncViewTask() {
  imageCache = new HashMap>();
}

protected Drawable doInBackground(View... views) {
  Drawable drawable = null;
  View view = views[0];
  if (view.getTag() != null) {
if (imageCache.containsKey(view.getTag())) {
SoftReference cache = imageCache.get(view.getTag().toString());
drawable = cache.get();
if (drawable != null) {
  return drawable;
}
}
try {
if (URLUtil.isHttpUrl(view.getTag().toString())) {//  If for network address. The connection url Download the pictures 
  URL url = new URL(view.getTag().toString());
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setDoInput(true);
  conn.connect();
  InputStream stream = conn.getInputStream();
  drawable = Drawable.createFromStream(stream, "src");
  stream.close();
} else {//  If it is local data, parse it directly 
  drawable = Drawable.createFromPath(view.getTag().toString());
}
} catch (Exception e) {
Log.v("img", e.getMessage());
return null;
}
  }
  this.mView = view;
  return drawable;
}

protected void onPostExecute(Drawable drawable) {
  if (drawable != null) {
ImageView view = (ImageView) this.mView;
view.setImageDrawable(drawable);
this.mView = null;
}}}


Related articles: