我正在使用Volley库在Android中制作应用程序,我想向onResponse()方法的loadAll()添加一个ProgressDialog,但是当我这样做时,轮子在该方法期间不会移动。

我曾尝试对onResponse和ProgressDialog本身使用AsyncTask,但是它甚至不会出现。如果有人可以帮助我,那将真的有帮助。

这是loadAll()方法:

public void loadAll() {
    checkPermissions();
    String tag_string_req = "string_req";
    final String TAG = AppController.class
            .getSimpleName();
    String url = "http://android.diggin.io/projectmanager/v1/all";

    pDialog = new ProgressDialog(this);
    pDialog.setMessage("Synchronizing...");
    pDialog.show();

    StringRequest strReq = new StringRequest(Request.Method.GET,
            url, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, response);
            try {
                JSONObject jsonObject = new JSONObject(response);
                if (!jsonObject.getBoolean("error")) {
                    SharedPreferences sharedPref = MainActivity.this.getSharedPreferences(getString(R.string.user_id), Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.putInt(getString(R.string.user_id), jsonObject.getInt("user_id"));
                    editor.commit();
                    JSONArray jsonProjects = jsonObject.getJSONArray("projects");
                    JSONArray jsonPhotos = jsonObject.getJSONArray("photos");
                    db.clearDB();
                    File dir = getDir("projectImages", Context.MODE_PRIVATE);
                    if (dir.isDirectory()) {
                        String[] children = dir.list();
                        for (int count = 0; count < children.length; count++)
                        {
                            boolean onlyThumbs = true;
                            File subDir = new File(dir, children[count]);
                            String[] subChildren = subDir.list();
                            for (int count2 = 0; count2 < subChildren.length; count2++)
                            {
                                File subSubDir = new File(subDir, subChildren[count2]);
                                String[] subSubChildren = subSubDir.list();
                                for (int count3 = 0; count3 < subSubChildren.length; count3++)
                                {
                                    if (subSubChildren[count3].startsWith("picture")) {
                                        onlyThumbs = false;
                                    }
                                }
                                if (onlyThumbs) {
                                    File file = new File(subSubDir.getPath());

                                    if (file.exists()) {
                                        String deleteCmd = "rm -r " + subSubDir.getPath();
                                        Runtime runtime = Runtime.getRuntime();
                                        try {
                                            runtime.exec(deleteCmd);
                                        } catch (IOException e) {
                                            Log.e("IOException",e.toString());
                                        }
                                    }
                                }
                            }
                            if (onlyThumbs) {
                                File file = new File(subDir.getPath());

                                if (file.exists()) {
                                    String deleteCmd = "rm -r " + subDir.getPath();
                                    Runtime runtime = Runtime.getRuntime();
                                    try {
                                        runtime.exec(deleteCmd);
                                    } catch (IOException e) {
                                        Log.e("IOException",e.toString());
                                    }
                                }
                            }
                        }
                    }
                    for (int i = 0; i < jsonProjects.length(); i++) {
                        JSONObject jsonProject = (JSONObject) jsonProjects.get(i);
                        Project project = new Project(jsonProject.getInt("id"),jsonProject.getString("title"),jsonProject.getInt("user_id"));
                        db.addProject(project);
                        JSONArray jsonWells = jsonProject.getJSONArray("wells");
                        for (int i2 = 0; i2 < jsonWells.length(); i2++)
                        {
                            JSONObject jsonWell = (JSONObject) jsonWells.get(i2);
                            Well well = new Well(jsonWell.getInt("id"),jsonWell.getString("number"),jsonWell.getInt("project_id"));
                            db.addWell(well);
                        }
                        JSONArray jsonTracks = jsonProject.getJSONArray("tracks");
                        for (int i2 = 0; i2 < jsonTracks.length(); i2++)
                        {
                            JSONObject jsonTrack = (JSONObject) jsonTracks.get(i2);
                            Track track = new Track(jsonTrack.getInt("id"),jsonTrack.getString("number"));
                            boolean inDb = false;
                            for (Track t : db.getAllTracks()) {
                                if(t.toString().equals(track.toString())) {
                                    inDb = true;
                                }
                            }
                            if (!inDb) {
                                db.addTrack(track);
                            }
                            Track_Well track_well = new Track_Well(db.getAllTrackWells().size() + 1, jsonTrack.getInt("id"), jsonTrack.getInt("well_id"));
                            db.addTrackWell(track_well);
                        }
                        JSONArray jsonSurfaces = jsonProject.getJSONArray("surfaces");
                        for (int i2 = 0; i2 < jsonSurfaces.length(); i2++)
                        {
                            JSONObject jsonSurface = (JSONObject) jsonSurfaces.get(i2);
                            Surface surface = new Surface(jsonSurface.getInt("id"),jsonSurface.getString("number"),jsonSurface.getInt("well_id"));
                            boolean inDb = false;
                            for (Surface s : db.getAllSurfaces()) {
                                if(s.toString().equals(surface.toString())) {
                                    inDb = true;
                                }
                            }
                            if (!inDb) {
                                db.addSurface(surface);
                            }
                            Track_Surface track_surface = new Track_Surface(db.getAllTrackSurfaces().size() + 1, (!jsonSurface.isNull("track_id") ? jsonSurface.getInt("track_id") : 0), jsonSurface.getInt("id"));
                            db.addTrackSurface(track_surface);
                        }
                        JSONArray jsonProfiles = jsonProject.getJSONArray("profiles");
                        for (int i2 = 0; i2 < jsonProfiles.length(); i2++)
                        {
                            JSONObject jsonProfile = (JSONObject) jsonProfiles.get(i2);
                            Profile profile = new Profile(jsonProfile.getInt("id"),jsonProfile.getString("number"),jsonProfile.getInt("well_id"));
                            boolean inDb = false;
                            for (Profile p : db.getAllProfiles()) {
                                if(p.toString().equals(profile.toString())) {
                                    inDb = true;
                                }
                            }
                            if (!inDb) {
                                db.addProfile(profile);
                            }
                            Track_Profile track_profile = new Track_Profile(db.getAllTrackProfiles().size() + 1, (!jsonProfile.isNull("track_id") ? jsonProfile.getInt("track_id") : 0), jsonProfile.getInt("id"));
                            db.addTrackProfile(track_profile);
                        }
                        JSONArray jsonFieldfinds = jsonProject.getJSONArray("fieldfinds");
                        for (int i2 = 0; i2 < jsonFieldfinds.length(); i2++)
                        {
                            JSONObject jsonFieldfind = (JSONObject) jsonFieldfinds.get(i2);
                            Fieldfind fieldfind = new FieldfindBuilder().id(jsonFieldfind.getInt("id"))
                                                                        .number(jsonFieldfind.getString("number"))
                                                                        .project_id(!jsonFieldfind.isNull("project_id") ? jsonFieldfind.getInt("project_id") : 0) // if (!jsonFieldfind.isNull("project_id")) {
                                                                        .well_id(!jsonFieldfind.isNull("well_id") ? jsonFieldfind.getInt("well_id") : 0)          //     well_id = jsonFieldfind.getInt("project_id");
                                                                        .track_id(!jsonFieldfind.isNull("track_id") ? jsonFieldfind.getInt("track_id") : 0)       // } else {
                                                                        .surface_id(!jsonFieldfind.isNull("surface_id") ? jsonFieldfind.getInt("surface_id") : 0) //     well_id = 0;
                                                                        .profile_id(!jsonFieldfind.isNull("profile_id") ? jsonFieldfind.getInt("profile_id") : 0) // }
                                                                        .user_id(jsonFieldfind.getInt("user_id")).buildFieldfind();
                            db.addFieldfind(fieldfind);
                        }
                    }
                    for(int i3 = 0; i3 < jsonPhotos.length(); i3++) {
                        JSONObject jsonPhoto = (JSONObject) jsonPhotos.get(i3);
                        File mainDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "ProjectManager");
                        String pathStart = mainDir.getPath() + "/";
                        Photo photo = new Photo(jsonPhoto.getInt("id"), jsonPhoto.getInt("user_id"), jsonPhoto.getString("imageable_type"), jsonPhoto.getInt("imageable_id"), pathStart + jsonPhoto.getString("image_path"),jsonPhoto.getString("description"),jsonPhoto.getString("metadata"),jsonPhoto.getString("wind"));
                        Log.d("LoadAll - Photos(" + i3 + ")", photo.toString());
                        String filename = photo.getDBImage_path();
                        File pictureFile = new File(mainDir, filename);
                        photo.setImage_path(pictureFile.toString());
                        if (!pictureFile.exists()) {
                            photo.setImage_path(photo.getThumbnailFromImage_path());
                            db.addPhoto(photo);
                            String image_str = jsonPhoto.getString("image");
                            byte[] byte_arr = Base64.decode(image_str, 0);
                            Bitmap bitmap = BitmapFactory.decodeByteArray(byte_arr, 0, byte_arr.length);
                            try {
                                createPicture(bitmap, photo);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            db.addPhoto(photo);
                            syncPhotos.add(photo);
                        }
                    }
                    getAllProjects();
                } else {
                    //Send message when username and/or password is incorrect
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MainActivity.this);
                            dlgAlert.setMessage("Something went wrong");
                            dlgAlert.setPositiveButton("OK", null);
                            dlgAlert.setCancelable(true);
                            dlgAlert.create().show();
                        }
                    });
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            pDialog.hide();
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            pDialog.hide();
        }
    }) {
        //Passing some request headers
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Authorization", apiKey);
            return headers;
        }
    };
    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

最佳答案

检查您的代码,似乎您可能在主线程上执行了数据库操作,这也许是进度对话框挂起的原因。
在后台线程(使用AsyncTask)中移动数据库操作即可完成操作。

10-04 14:53