Volley library and AsyncTask

1.1k views Asked by At

I'm using Volley library for my Android project. Here is what I'm trying to do: I have a login screen in my app, from where I'll take user details and send it to the server through JSON request, which in response gives the verification status. Then immediately I'll make another JSON request to server to fetch other user details and save it to local DB using greenDao ORM. After the details are saved to DB, i'll navigate user to next activity and display the fetched details from local DB. But, as soon as I navigate to next activity in onResponse() method, it's not showing up the details, meaning data fetched from server is not currently saved in DB. Is it because Volley is doing the things in background and it's not completed yet? I know that Volley does its job on a separate thread in background and there is no need to use AsyncTask for that, but onPostExecute() can guarantee the task of saving to DB is completed and it's ok to navigate to next activity.
If you didn't get my problem, here is my code. LoginActivity.java

 package com.example.example.nxtstepzone;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast
import com.android.volley.toolbox.RequestFuture;
import com.example.example.nxtstepzone.Networking.AppController;
import com.example.example.nxtstepzone.Networking.DataFromServer;


  public class LoginActivity extends FragmentActivity {
Context context;
    Button l;
    EditText email,password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);


          email = (EditText)findViewById(R.id.email);
        password=(EditText)findViewById(R.id.password);


     l=(Button)findViewById(R.id.button_login);
     l.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

      DataFromServer ds= new DataFromServer(LoginActivity.this);
      ds.downloadDataLogin(email.getText().toString(), password.getText().toString());

       }});
     }
 }

Here is DataFromServer Class where I have implemented the methods

package com.example.nxtstepzone.Networking;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.example.example.nxtstepzone.HomeActivity;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.orhanobut.hawk.Hawk;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import de.greenrobot.dao.query.QueryBuilder;
import example.DaoMaster;


/**
 * Created by Prathya on 6/14/2015.
 */
public class DataFromServer {

    Context context;
    private Keys keys;
    DaoMaster.DevOpenHelper helper;
    SQLiteDatabase db;
    DaoMaster daoMaster;
    DaoSession session;
    UserDao userDao;
    PostDao postDao;
    QueryBuilder qb;



    public DataFromServer(Context context){
        this.context = context;
        keys = new Keys();
        helper = new DaoMaster.DevOpenHelper(context,"nxtstepz",null);
        db =helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        session = daoMaster.newSession();
        userDao= session.getUserDao();
        postDao = session.getPostDao();
    }


    public void downloadDataLogin(final String email,String password){
        final ProgressDialog progressDialog;
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);
        progressDialog.show();
                String loginurl = "http://example.com/webservice/webservice.php?oper=checklogin&username="+email+"&password="+password;



        JsonObjectRequest req = new JsonObjectRequest(loginurl, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {


                        try {
                           int status = response.getInt("status");

                            if(status==1){
                                Hawk.init(context);
                                Hawk.put("userid", Integer.parseInt(response.getString(keys.KEY_USER_ID)));
                                Toast.makeText(context, "Logged in" , Toast.LENGTH_SHORT).show();
                                User user= new User();
                                user.setId(Long.parseLong(response.getString(keys.KEY_USER_ID))); //some details saved to DB
                                userDao.insertOrReplace(user); 
                                downloadDataOnLogin(Integer.parseInt(response.getString(keys.KEY_USER_ID)),2,0); // request for further details using downloadDataOnLogin method

                                    if(progressDialog.isShowing()){
                                    progressDialog.dismiss();
                                }

                                Intent in = new Intent(context, HomeActivity.class); //navigating to next activity
                                in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(in);


                            }
                            else{
                                if(progressDialog.isShowing()){
                                    progressDialog.dismiss();
                                }
                                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                builder.setTitle("Authentication Failed !");
                                builder.setMessage("Incorrect username or password")
                                        .setCancelable(false)
                                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {

                                            }
                                        });
                                AlertDialog alert = builder.create();
                                alert.show();


                            }


                        }
                        catch (Exception e){
                           Toast.makeText(context,"Server error!..",Toast.LENGTH_SHORT).show();

                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if(progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("Network Error");
                builder.setMessage("Couldn't connect to server.Check internet connection and Try again")
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();


            }
        });

        AppController.getInstance().addToRequestQueue(req);


    }


     public void downloadDataOnLogin(int userid,int post_type_id, int post_page_number){

         String onloginurl="http://example.com/webservice/webservice.php?oper=getallactivities&userid="+userid+"&type="+post_type_id+"&page="+post_page_number;
         JsonArrayRequest req = new JsonArrayRequest(onloginurl, new Response.Listener<JSONArray>(){
             @Override
             public void onResponse(JSONArray response) {
                 for(int i=0;i<response.length();i++){
                     try {
                         JSONObject jsonObject = response.getJSONObject(i);
                         Post post = new Post();
                      post.setPosttypeid(jsonObject.getString("post_type_id"));
                      //here I'm saving the details to database. 
                         postDao.insertOrReplace(post);
                    }catch (JSONException e){

                     }
                 }
             }
         }, new Response.ErrorListener(){
             @Override
             public void onErrorResponse(VolleyError error) {

             }
         });

         AppController.getInstance().addToRequestQueue(req);

    }


}

Note that I'm navigating to next activity after the code of saving data to DB. But still, when the new Activity is started, Still, the data is not saved to DB and I have confirmed this through putting breakpoints. Should I use AsyncTask's onPostExecute() to ensure that background tasks are completed and I can proceed to next activity? Or is there any way of doing this using callback interfases ?

1

There are 1 answers

0
Muthu On

First you need to create an Interface as follows

interface RequestComplete{  
void oncompleted();  
}  

and implement them in your main activity

public class LoginActivity extends FragmentActivity implements RequestComplete {
   .......
  @override
    void oncompleted(){
    //Your navigation code
    }
}

and inside

public void downloadDataOnLogin(int userid,int post_type_id, int post_page_number){
  .........
  postDao.insertOrReplace(post);
 //after your insert completed 
 ((RequestComplete)context).RequestComplete();
}

Above example gives you an idea how it works.