图像上载期间的ProgressDialog无法正确显示

时间:2011-12-30 17:23:42

标签: android

我在图片上传过程中出现了正确显示ProgressDialog的问题。 我在AsynkTask中创建了HTTPRequest,并使用doInBackground()和progressUpdate()方法更新了进度条,但是出了点问题。当我从主活动启动任务时,ProgressDialog不会启动,但它只在上传结束后显示。

以下是任务的代码:

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();
}
}

这是从主Activity类调用任务的代码部分:

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);
    }
}

感谢您的支持;)

1 个答案:

答案 0 :(得分:0)

尝试在那时传递真实的上下文,我相信你试图将异步任务的结果传递给String变量“result”。主线程必须等到异步任务完成,因此它挂起,因此无法显示对话框。