0

i got some problem to show correctly a ProgressDialog during an image upload. I've made the HTTPRequest in a AsynkTask and i update the progress bar using doInBackground() and progressUpdate() method, but something's wrong. When i start the Task from the main activity the ProgressDialog does't start but it shows itself only after the end of the upload.

Here is the code of the Task:

public class HTTPReqPostTask extends AsyncTask<Void, Integer, String>
{
private funzioni func = new funzioni();
private static final String TAG = "MotoRnUpload";
private ProgressBar progress;
private final Foto img;
private final Album al;
private final URL endpoint;
private String result;
private byte[] bytes;
private ProgressDialog dialog;
private Activity parent;

public HTTPReqPostTask(Activity act,final Foto f,final Album a,final URL u){
    parent = act;
    img = f;
    al = a;
    endpoint = u;
    result = null;
    bytes = func.imgToBytes2(img);        
}

@Override
protected void onPreExecute() {
    dialog = new ProgressDialog(parent);
    dialog.setMessage("Uploading...");
    dialog.setIndeterminate(false);
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    dialog.setProgress(0);        
    dialog.show();        
}

/*
 * 
 */
@Override
protected String doInBackground(final Void... args)
{
final String CrLf = "\r\n";

int i=0,w,h; 
HttpURLConnection urlc = null;
DataOutputStream printout;
Bitmap b_img = BitmapFactory.decodeFile((img.getFile()).getAbsolutePath());

w = b_img.getWidth();
h = b_img.getHeight();

if(img.getRotationL() == 1 || img.getRotationR() == 1){
        int dim;
        dim = w;
        w = h;
        h = dim;
}

String message1="",message2="",message3="",message4="",message5="",message6="",message7="",message8="",
                message9="",message10="",message11="",message12="",message14="";
try
{
        urlc = (HttpURLConnection) endpoint.openConnection();
        try
        {
                urlc.setRequestMethod("POST");
                urlc.setRequestProperty("Connection", "Keep-Alive");
        } catch (ProtocolException e)
                {
                    Log.e(TAG, e.getMessage(),e.fillInStackTrace());
                }
        urlc.setDoOutput(true);
        urlc.setDoInput(true);
        urlc.setUseCaches(false);
        urlc.setAllowUserInteraction(false);

        message1 += "-----------------------------4664151417711" + CrLf;
        message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test"+bytes.length+".jpg\"" + CrLf;
        message1 += "Content-Type: image/jpeg" + CrLf;
        message1 += CrLf;
        // the image is sent between the messages in the multipart message.
        message2 += CrLf + "-----------------------------4664151417711--" + CrLf;
        //dati normali
        message3 += "-----------------------------4664151417711" + CrLf;
        message3 += "Content-Disposition: form-data; name=\"nomeFoto\"" + CrLf +CrLf;
        //
        message4 += "-----------------------------4664151417711" + CrLf;
        message4 += "Content-Disposition: form-data; name=\"idCat\"" + CrLf +CrLf;
        //
        message5 += "-----------------------------4664151417711" + CrLf;
        message5 += "Content-Disposition: form-data; name=\"idAlbum\"" + CrLf +CrLf;
        //
        message6 += "-----------------------------4664151417711" + CrLf;
        message6 += "Content-Disposition: form-data; name=\"nomeAlbum\"" + CrLf +CrLf;
        //
        message7 += "-----------------------------4664151417711" + CrLf;
        message7 += "Content-Disposition: form-data; name=\"idUser\"" + CrLf +CrLf;
        //
        message8 += "-----------------------------4664151417711" + CrLf;
        message8 += "Content-Disposition: form-data; name=\"isPrivato\"" + CrLf +CrLf;
        //
        message9 += "-----------------------------4664151417711" + CrLf;
        message9 += "Content-Disposition: form-data; name=\"isNew\"" + CrLf +CrLf;
        //
        message10 += "-----------------------------4664151417711" + CrLf;
        message10 += "Content-Disposition: form-data; name=\"width\"" + CrLf +CrLf;
        //
        message11 += "-----------------------------4664151417711" + CrLf;
        message11 += "Content-Disposition: form-data; name=\"height\"" + CrLf +CrLf;
        //
        message12 += "-----------------------------4664151417711" + CrLf;
        message12 += "Content-Disposition: form-data; name=\"gps_lat\"" + CrLf +CrLf;
        //
        message14 += "-----------------------------4664151417711" + CrLf;
        message14 += "Content-Disposition: form-data; name=\"gps_lon\"" + CrLf +CrLf;
        //
        urlc.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
        // might not need to specify the content-length when sending chunked data.
        //urlc.setRequestProperty("Content-Length", String.valueOf((message1.length() + String.valueOf(message2.length()) + String.valueOf(bytes.length) )));


        printout = new DataOutputStream (urlc.getOutputStream());
        //
        // invia il nome del file
        //
        printout.write(message3.getBytes());
        printout.writeBytes(img.getNome());
        printout.writeBytes(CrLf);
        //
        printout.write(message10.getBytes());
        printout.writeBytes(Integer.toString(w));
        printout.writeBytes(CrLf);
        //
        printout.write(message11.getBytes());
        printout.writeBytes(Integer.toString(h));
        printout.writeBytes(CrLf);
        //
        printout.write(message7.getBytes());
        printout.writeBytes(Integer.toString(img.getIdUser()));
        printout.writeBytes(CrLf);
        //
        printout.write(message9.getBytes());
        printout.writeBytes(Boolean.toString(al.isNew()));
        printout.writeBytes(CrLf);
        //
        if(img.hasGps()){
                printout.write(message12.getBytes());
                printout.writeBytes(img.getGpsLat());
                printout.writeBytes(CrLf);
                //
                printout.write(message14.getBytes());
                printout.writeBytes(img.getGpsLon());
                printout.writeBytes(CrLf);
                //
        }
        //
        if(al.isNew()){
                printout.write(message4.getBytes());
                printout.writeBytes(Integer.toString(al.getIdCat()));
                printout.writeBytes(CrLf);
                //
                printout.write(message6.getBytes());
                printout.writeBytes(al.getNome());
                printout.writeBytes(CrLf);
                //
                printout.write(message8.getBytes());
                printout.writeBytes(Boolean.toString(al.isPrivato()));
                printout.writeBytes(CrLf);
        }else{
                printout.write(message5.getBytes());
                printout.writeBytes(Integer.toString(al.getId()));
                printout.writeBytes(CrLf);
        }
        //
        // invia la foto
        //
        printout.write(message1.getBytes());

        // SEND THE IMAGE
        int size = 1024;    
        do{         
            publishProgress(i);
            if((i+size)>bytes.length){
                size = bytes.length - i;
            }
            printout.write(bytes, i, size);
            i+=size;                
        }while(i<bytes.length);
        publishProgress(bytes.length);
        //
        printout.write(message2.getBytes()); 
        printout.flush ();
        printout.close ();
        Log.i(TAG, "Immagine inviata");            
        //Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null)
        {
            sb.append(line);
        }   
        rd.close();
        result = sb.toString();
} catch (Exception e)
{
    Log.e(TAG,e.toString(),e.fillInStackTrace());
}
return result;
}

@Override
protected void onProgressUpdate(final Integer... values) {
    dialog.setProgress(values[0]);
}

@Override
protected void onPostExecute(final String res) {
    dialog.dismiss();
}
}

This is the part of code that call the task from the main Activity class:

public void onClick(View view) {
    if(view.getId() == R.id.button1){
        try{
            String result;
            JSONObject info_upload;
            result = new HTTPReqPostTask(MainActivity.this,foto,alb,new               URL(urlUpload)).execute().get();
            info_upload = new JSONObject(result);
            if(info_upload.getString("stato").equals("fail")){
                funzioni.popUp(MainActivity.this,"Errore caricamento foto: "+info_upload.getString("info"));                    
            }else{
                funzioni.popUp(MainActivity.this,"Foto caricata correttamente su MotoRn");
                if(info_upload.getString("stato").equals("create")){
                    alb.setId(info_upload.getInt("id_album"));
                    alb.setIsNew(false);
                }
            }
        }catch(MalformedURLException mue){
            Log.e(TAG,mue.toString(),mue.fillInStackTrace());
            funzioni.popUp(MainActivity.this, mue.getMessage()+" : "+mue.getLocalizedMessage());
        }catch(Exception e){
            Log.e(TAG,e.toString(),e.fillInStackTrace());
            funzioni.popUp(MainActivity.this, e.getMessage()+" : "+e.getLocalizedMessage());
        }
    }else if(view.getId() == R.id.b_open ){
        startActivityForResult(new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI), SELECT_IMAGE_CODE);
    }
}

Thank you for the support ;)

  • 1
    Have you seen http://stackoverflow.com/questions/2702695/android-async-task-progressdialog-isnt-showing-until-background-thread-finishes ? Try hard coding the context instead of using what you passed in the constructor (dialog = new ProgressDialog(MyClass.this) OR dialog = new ProgressDialog(getApplicationContext()) ) maybe? – Jack Dec 30 '11 at 17:37
  • Already done but nothing seems to change. If i use getApplicationContext() i get the error "unable to add window - token null is not for an application". I've read the post you told me but it doesn't solve my issue. – Gianluca Suzzi Dec 30 '11 at 18:13

1 Answers1

0

try to pass the real context at that time and i believe you are trying to pass the result of the async task to the String variable "result". The main thread has to wait until the async task has finished, so its hanging and thus cannot show the dialog.

NikkyD
  • 2,209
  • 1
  • 16
  • 31
  • Yes, i think that's the problem. How can i solve that? Shall i execute the asyncTask in a separate thread? Thank you for your answer ;) – Gianluca Suzzi Dec 30 '11 at 18:45
  • Async task is already another thread. The onPre and onPost methods run on the main thread, the onBackG runs on a seperate thread. You cannot use the result the second you start the task, you have to somehow code it that it can come back later, thats the point of it. – NikkyD Dec 30 '11 at 18:58
  • Ok i solved not using the result but now i've to figure out how to get the result in other way. Thank you for the advice ;) – Gianluca Suzzi Dec 30 '11 at 21:41
  • The trick is, while the dialog is displaying, the main thread is useless, because it displays the loading symbol. But it can still respond to calls etc. So once ur task is finished, let it handle all the stuff that you had in your onclick in the onPost. And AFTER you handled it, you dismiss the dialog. The user will see a loading symbol or sth like that and once it vanishes he sees the new content etc – NikkyD Dec 30 '11 at 22:08
  • This is exactly what i did, i think is the best way to handle that. Now it works fine, there is only a little thing i've to fix. The progressDialog upgrade to fast and it arrives to 100% before the image uploading is complete. But maybe for that question i've to open another post. Thank you for your support, best regards and happy new year from Italy ;) – Gianluca Suzzi Dec 31 '11 at 11:57