Android Asynchronous Interface implementation

Source: Internet
Author: User

When using asynchronous request network data, an asynchronous class is defined each time an interface is requested, in order to avoid some unnecessary steps, abstract the asynchronous class

The following uses a login interface to compare the use of the interface before and after the login using the POST request

simplifies the implementation of pre-async:

class Loginasytask extends Asynctask<void, Integer, string>{
         @Override
         protected void OnPreExecute () {
             super.onpreexecute ();
        }
        
         @Override
        protected String doinbackground (Void ... arg0) {

Parameters for the POST request
map<string, string> params = new hashmap<string, string> ();
Params.put ("username", Meditusername.gettext (). toString ());
Params.put ("Password", Medituserpwd.gettext (). toString ());

try {

//Send request, accept string returned by server
return Postutil.sendpostrequest (loginurl,params);
} catch (Clientprotocolexception e) {
e.printstacktrace ();
} catch (IOException e) {
e.printstacktrace ();
            }
return null;
        }
        
@Override
protected void OnPostExecute (String result) {
if (result! = null) {
Jsontokener jsonparser = new Jsontokener (result);
//Not read any JSON text at this time, direct reading is a Jsonobject object.
Jsonobject Loginjson;
try {
Loginjson = (jsonobject) jsonparser.nextvalue ();
//The next step is the operation of the JSON object.
loginjson.getstring ("message");
loginjson.getint ("code");
if (Loginjson.getint ("code") = = 0) {
Intent Intent = new Intent (loginactivity.this,mainactivity.class);
startactivity (intent);
Toast.maketext (loginactivity.this, "login successful", 0). Show ();
}else{
Toast.maketext (loginactivity.this, "Login Failed", 0). Show ();
                    }
} catch (Jsonexception e) {
//TODO auto-generated catch block
e.printstacktrace ();
                }
LOGUTIL.E ("Login", result.tostring ());
            }
Super.onpostexecute (result);
        }
        
    }

After simplifying the asynchronous use of the interface

First define an interface, which includes an abstract OnPostExecute (Object object) method

Asynccallback.class

Public interface AsyncCallback {

public void OnPostExecute (Object object);
}

Then define an abstract class that is asynchronous

Public abstract class abstractpostasynctask<void, Progress, result> extends Asynctask<void, Progress, result>{

private Httputil mhttputil;
private Gson Gson;
private class<result> Result;

protected AsyncCallback masynccallback;
    
Public Abstractpostasynctask (Class<result> T, AsyncCallback AsyncCallback) {
this.masynccallback = AsyncCallback;
this.result = t;
This.gson = new Gson ();
this.mhttputil = new Httputil ();
    }
    

@Override
protected Result doinbackground (Void ... arg0) {
String str = null;
try {
str = postutil.sendpostrequest (Getrequesturl (), Getrequestparams ());
return Parse (str, result);
} catch (Clientprotocolexception e) {
e.printstacktrace ();
} catch (IOException e) {
e.printstacktrace ();
        }
return null;
    }
    
@Override
protected void OnPostExecute (result result) {
Super.onpostexecute (result);
This.mAsyncCallBack.onPostExecute (result);
    }
    
    
Private Result Parse (String str, class<result> t) {
result = null;
Objectmapper mapper = Mapperutil.getmapper ();
//Parse JSON data as "request" Object
try {
result = Mapper.readvalue (str,t);
} catch (Jsonparseexception e) {
e.printstacktrace ();
} catch (Jsonmappingexception e) {
e.printstacktrace ();
} catch (IOException e) {
e.printstacktrace ();
        }
return result;
    }
    
protected abstract map<string, string> getrequestparams ();
    
protected abstract String getrequesturl ();
}

Finally, the abstract method of this abstract class and the OnPostExecute (Object object) method in the AsyncCallback interface are implemented where needed

Public class Allsitesasytask extends Abstractgetasynctask<void, Void, sitejson> {
        
@Override
protected void OnPreExecute () {
Super.onpreexecute ();
        }

Public Allsitesasytask (Class<loginjson> T, AsyncCallback AsyncCallback) {
Super (T, AsyncCallback);
        }

@Override
Public String Getrequesturl () {
return constants.login_url;
        }
    }

Implementing Asynchronous execution

Allsitesasytask allsitesasytask = new Allsitesasytask (Sitejson.class, new AsyncCallback () {
@Override
public void OnPostExecute (Object object) {
Setallstationtolist (object);
Progressdialog.dismiss ();
}
});
Allsitesasytask.execute ();

The Postutil tool class used to request the post data

public class Postutil {

/**
*
* @param params parameter array
* @return
*/
public static string sendpostrequest (string url, map<string, string> params) throws Clientprotocolexception, IOException {
Defaulthttpclient httpclient = new Defaulthttpclient ();
HttpPost HttpPost = new HttpPost (URL);

list<namevaluepair> pairs = new arraylist<namevaluepair> (); Store Request Parameters
if (params! = null &&!params.isempty ()) {
For (map.entry<string, string> entry:params.entrySet ()) {
Pairs.add (New Basicnamevaluepair (Entry.getkey (), Entry.getvalue ()));
}
}
urlencodedformentity entity = new Urlencodedformentity (pairs, HTTP. UTF_8);
Httppost.setentity (entity);
HttpResponse response = Httpclient.execute (HttpPost);
if (Response.getstatusline (). Getstatuscode () = = HTTPURLCONNECTION.HTTP_OK) {
Return entityutils.tostring (Response.getentity ());
}
return null;
}

}

Android Asynchronous Interface implementation

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.