ProgressBar in asynctask is not showing on upload

后端 未结 2 1423
暖寄归人
暖寄归人 2020-12-06 15:18

Can someone tell me, why progressbar isnt showing when picture is being uploaded. I copied asynctask structure from my old project where it works. In my old project i use as

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 15:59

    I found this library which is perfect to accomplish the upload task and also provide a progress handler which could be used to set the value of a ProgressBar:

    https://github.com/nadam/android-async-http

    It could be used like the following... Set onClickHandler for the upload Button:

    @Override
    public void onClick(View arg0) {
        try {
            String url = Uri.parse("YOUR UPLOAD URL GOES HERE")
                    .buildUpon()
                    .appendQueryParameter("SOME PARAMETER IF NEEDED 01", "VALUE 01")
                    .appendQueryParameter("SOME PARAMETER IF NEEDED 02", "VALUE 02")
                    .build().toString();
    
            AsyncHttpResponseHandler httpResponseHandler = createHTTPResponseHandler();
    
            RequestParams params = new RequestParams();
            // this path could be retrieved from library or camera
            String imageFilePath = "/storage/sdcard/DCIM/Camera/IMG.jpg";
            params.put("data", new File(imageFilePath));
    
            AsyncHttpClient client = new AsyncHttpClient();
            client.post(url, params, httpResponseHandler);
        } catch (IOException e) {
            e.printStackTrace();                
        }
    }
    

    then add this method to your activity code:

    public AsyncHttpResponseHandler createHTTPResponseHandler() {
        AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }
    
            @Override
            public void onProgress(int position, int length) {
                super.onProgress(position, length);
    
                progressBar.setProgress(position);
                progressBar.setMax(length);
            }
    
            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
            }
    
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
            }
    
            @Override
            public void onFinish() {
                super.onFinish();
            }
        };
    
        return handler;
    }
    

提交回复
热议问题