-1

When the app first run in the device I'm fetching the datas from the database and saved it to the SQLite so that the user can use it while offline.

My code is this.

public class AsyncDatas extends AsyncTask<Void,Void,Void> {
    private Context context;
    private List<ModelAccounts> accountDatas;
    private List<ModelPoi> poiDatas;
    private List<ModelComments> commentDatas;
    private List<ModelImage> imageDatas;
    private List<ModelFavorite> favoriteDatas;
    final String MY_PREFS_NAME = "USER";
    private List<ModelAccounts> accountDatas2;
    private int count;
    private Bitmap[] thumbnails;
    private Activity activity;

    public AsyncDatas(Context context,Activity activity){
        this.context = context;
        this.activity = activity;
    }


    @Override
    protected Void doInBackground(Void... params) {
        RequestQueue requestUsers = Volley.newRequestQueue(context);
        JsonObjectRequest jsonObjectUsers = new JsonObjectRequest(Request.Method.POST,
                GET_USER_URL, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                ModelAccounts modelAccounts = new ModelAccounts();
                try {
                    JSONArray jsonArray = response.getJSONArray("poi");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        int getID = jsonObject.getInt("id");
                        accountDatas = new Select().from(ModelAccounts.class).where(Condition.column(ModelAccounts$Table.USER_ID).is(getID)).queryList();
                        if (accountDatas.size() == 0) {
                            modelAccounts = new ModelAccounts();
                            modelAccounts.setFname(jsonObject.getString("firstname"));
                            modelAccounts.setLname(jsonObject.getString("lastname"));
                            modelAccounts.setUname(jsonObject.getString("username"));
                            modelAccounts.setPword(jsonObject.getString("password"));
                            modelAccounts.setImg(jsonObject.getString("img"));
                            modelAccounts.setUser_id(String.valueOf(getID));
                            modelAccounts.save();
                        }
                        Log.e("DONE","DONE USEr");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        requestUsers.add(jsonObjectUsers);


        RequestQueue requestFavorites = Volley.newRequestQueue(context);
        JsonObjectRequest jsonObjectFav = new JsonObjectRequest(Request.Method.POST,
                GET_FAV_URL, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                ModelFavorite modelFavorite = new ModelFavorite();
                try {
                    JSONArray jsonArray = response.getJSONArray("poi");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        int getID = jsonObject.getInt("id");
                        favoriteDatas = new Select().from(ModelFavorite.class).where(Condition.column(ModelFavorite$Table.FAVORITE_ID).is(getID)).queryList();
                        if (favoriteDatas.size() == 0) {
                            modelFavorite = new ModelFavorite();
                            modelFavorite.setLatitude(jsonObject.getString("latitude"));
                            modelFavorite.setUser_id(jsonObject.getString("user_id"));
                            modelFavorite.setType(jsonObject.getString("type"));
                            modelFavorite.setFavorite_id(String.valueOf(getID));
                            modelFavorite.save();
                        }
                    }
                    Log.e("DONE","DONE FAV");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        requestFavorites.add(jsonObjectFav);



        RequestQueue requestPOI = Volley.newRequestQueue(context);
        JsonObjectRequest jsonObjectPOI = new JsonObjectRequest(Request.Method.POST,
                INSERT_POI_URL, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                ModelPoi modelPoi = new ModelPoi();
                try {
                    JSONArray jsonArray = response.getJSONArray("poi");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        int getID = jsonObject.getInt("id");
                        poiDatas = new Select().from(ModelPoi.class).where(Condition.column(ModelPoi$Table.POI_ID).is(getID)).queryList();
                        if(poiDatas.size()==0){
                            modelPoi = new ModelPoi();
                            modelPoi.setPOI(jsonObject.getString("POI"));
                            modelPoi.setPOIAddress(jsonObject.getString("POIAddress"));
                            modelPoi.setPOIType(jsonObject.getString("POIType"));
                            modelPoi.setPOILat(jsonObject.getString("POILat"));
                            modelPoi.setPOILong(jsonObject.getString("POILong"));
                            modelPoi.setPOIInfo(jsonObject.getString("POIInfo"));
                            modelPoi.setPoi_id(String.valueOf(getID));
                            modelPoi.save();
                        }
                        Log.e("DONE","DONE POI");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }

        });
        requestPOI.add(jsonObjectPOI);



        RequestQueue requestComments = Volley.newRequestQueue(context);
        JsonObjectRequest jsonObjectComments = new JsonObjectRequest(Request.Method.POST,
                COMMENTS_URL, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                ModelComments modelComments;
                try {
                    JSONArray jsonArray = response.getJSONArray("poi");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        int getID = jsonObject.getInt("id");
                        commentDatas = new Select().from(ModelComments.class).where(Condition.column(ModelComments$Table.COMMENT_ID).is(getID)).queryList();
                        if (commentDatas.size() == 0) {
                            modelComments = new ModelComments();
                            modelComments.setLatitude(jsonObject.getString("latitude"));
                            modelComments.setComment_id(jsonObject.getString("id"));
                            modelComments.setComment(jsonObject.getString("comment"));
                            modelComments.setDate(jsonObject.getString("date"));
                            modelComments.setTitle(jsonObject.getString("title"));
                            modelComments.setUser_id(jsonObject.getString("user_id"));
                            modelComments.setRating(jsonObject.getString("rating"));
                            modelComments.setComment_id(String.valueOf(getID));
                            modelComments.save();
                        }
                        Log.e("DONE","DONE COMMENTS");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        requestComments.add(jsonObjectComments);



        RequestQueue requestImage = Volley.newRequestQueue(context);
        JsonObjectRequest jsonObjectImage = new JsonObjectRequest(Request.Method.POST,
                GET_IMAGE_URL, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                ModelImage modelImage = new ModelImage();
                try {
                    JSONArray jsonArray = response.getJSONArray("poi");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        int getId = jsonObject.getInt("id");
                        imageDatas = new Select().from(ModelImage.class).where(Condition.column(ModelImage$Table.IMAGE_ID).is(getId)).queryList();
                        if (imageDatas.size()==0) {
                            modelImage = new ModelImage();
                            modelImage.setLatitude(jsonObject.getString("latitude"));
                            modelImage.setImg(jsonObject.getString("imagepath"));
                            modelImage.setUser_id(jsonObject.getString("user_id"));
                            modelImage.setDatetime(jsonObject.getString("datetime"));
                            modelImage.setImage_id(String.valueOf(getId));
                            modelImage.save();
                        }
                        Log.e("DONE","DONE IMG");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        requestImage.add(jsonObjectImage);






        final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};
        final String orderBy = MediaStore.Images.Media._ID;
        Cursor imagecursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
                null, orderBy);
        int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
        this.count = imagecursor.getCount();
        this.thumbnails = new Bitmap[this.count];

        Variable.IMAGES = new ArrayList<>();
        for (int i = 0; i < this.count; i++) {
            imagecursor.moveToPosition(i);
            int id = imagecursor.getInt(image_column_index);
            int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
            thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
                    context.getContentResolver(), id,
                    MediaStore.Images.Thumbnails.MICRO_KIND, null);
            Variable.IMAGES.add("file://" + imagecursor.getString(dataColumnIndex));
            Log.e("IMAGE","DOME IMAGE");
        }

}

Sometimes it does work, Sometimes it doesn't.
Is there anyway to smoothen the process in the above codes?
Sometimes it work means, All datas fetch.
Sometimes it doesn't means, only fewdatas fetched.
Like only the first RequestQueue work..
Thanks.

Charles Galvez
  • 1,100
  • 5
  • 19
  • 41
  • Then what should i do? That's what i know so far. so i used it. thanks – Charles Galvez Dec 07 '15 at 12:54
  • find similar problem using fx google and use the solution provided there. Which will be in short: 1. chain the async method( request next one when prev finished) calls or 2. us some kind of semaphore and wait till all executed ... of course that will be also nice to understand what is going on with your code now - understanding the basics of async callbacks (**like: the code request is finished in onResponse, not right after you put it into request queue**) – Selvin Dec 07 '15 at 13:01
  • Thanks sir. I'll try all your inputs. thanks. I'll be back if the problem is still there. thanks – Charles Galvez Dec 07 '15 at 13:11
  • ok one more thing to be sure that you understand ... `requestUsers.add(jsonObjectUsers);` will not wait till `jsonObjectUsers` request finish ... it's like "fire and forget" ... (well not exactly "forget" as it returns `Future` which can be "turned" into synchronus call via `get` ... which will be also the easiest way to fix your code ... but no necessary the good way) ... another problem is "sir" in you comment ... i'm not "sir", just "you" ... – Selvin Dec 07 '15 at 13:16
  • Sorry. Thank you. Okay i got it. – Charles Galvez Dec 07 '15 at 13:19
  • for me the accepted way is 1. do not use AsyncTask at all as Volley is asynchrouse allready ... 2. do not use multiple request queue - use single ... 3. at the place where you have now `Log.e("DONE","DONE FAV");` start next request (`jsonObjectPOI`) and `Log.e("DONE","DONE POI");` starts `jsonObjectComments` ... and finally `Log.e("DONE","DONE IMG");` put the whole code after `requestImage.add(jsonObjectImage);` (edit: or maybe .... start the AsyncTask there with only this code ...) – Selvin Dec 07 '15 at 13:21
  • In short I will put every request inside of onresponse? – Charles Galvez Dec 08 '15 at 00:54

1 Answers1

-2

You are doing to much work in one AsyncTask. Also for readability of the code, i recommend divide this code into smaller chunks perhaps one task for each API(web-service) call. then you will have all the data you need. decide the priority and then cal the tasks accordingly.

  • Then there's no other process to do this but just to divide the code.? so if i have 5 web service, i will have 5 asynctasks? – Charles Galvez Dec 07 '15 at 12:55
  • No write a simplified code.eg. write an asynctask which will have the functionality to call the api with request params and which wil return the response. then call this asynce task 5 times for each api then process the responce. Code Reusability is your answer. – TheAndroidFreak Dec 07 '15 at 12:58
  • Someone's comment that i should not use async method's inside asyncmethod.. but then i will try your suggestion. – Charles Galvez Dec 07 '15 at 13:01
  • ok.. plenty of libraries are there for api calls. try them too. – TheAndroidFreak Dec 07 '15 at 13:04
  • I'm almost done with my project. Changing libraries is not best option for me. :'( – Charles Galvez Dec 07 '15 at 13:07