flo flo - 1 year ago 73
Android Question

How to implement a login in Android using Volley?

I have a LoginActitvity with two textfields for the username and password and a login-button. When the user presses the button, the app starts an async task. The async task implements my VolleyHandler. It checks if the login parameters are correct and fetches some user data (using volley and json). While doing this, a ProgressDialog appears. When the async task is finished, it starts an intent to the MainActivity in the onPostExecute method.

Now to my question: Is it a good idea to make volley-requests in the async task, or do you have a better solution?


Answer Source

You cannot use asynctask. Volley care about it. You can use callback for work with data and ui. Looks like this:

public class LoginActivity extends SinglePaneActivity implements DownloadCallback {


public void sendRequest(){
  Downloader download = new Download(this);
  downloader.download(userName, password);

public void requestFinish(){
 //... continue


public interface DownloadCallback {
    void requestFinish(); 

in class downloader

private RequestQueue requestQueue;
DownloadCallback mcallback;

public void Downloader(DownloadCallback callback){
   mCallback = callback;
   requestQueue = Volley.newRequestQueue(mContext);

private void initVolleyListeners() {

    mSuccessListener = new Response.Listener<JSONObject>() {
        public void onResponse(JSONObject response) {

    mErrorListener = new Response.ErrorListener() {
        public void onErrorResponse(VolleyError error) {

public void download(String user, String pass){
     JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, createJson(user, pass), mSuccessListener , mErrorListener ) {
        //header for send JSON to server
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            return headers;

   requestQueue.add(jsonObjectRequest );

And one point. Don't send user name in json. You send it as param in header. Use this application/x-www-form-urlencoded and set up pass an username as params in header.

Update: Now It will work. Sorry I wrote it in a hurry. Article about how callback work

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download