gpt4 book ai didi

android - 上载图片时,ProgressDialog不显示

转载 作者:行者123 更新时间:2023-12-03 13:12:56 25 4
gpt4 key购买 nike

我有一个用于将图像上传到服务器的类。
上传时,我想显示一个progressDialog来显示上传进度。
但是进度条没有显示出来。
这是我的ImageUploader类:

package com.OBO.Bandenanalyse;

//Imagine Imports here

public class ImageUploader {
private Context context;
private ProgressDialog dialog;

public ImageUploader(Context ctx) {
this.context = ctx;
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
dialog = new ProgressDialog(context);
dialog.setCancelable(false);
dialog.setMessage("Uploading Image... Please wait!");
dialog.show();
}
});
}

private static String serverResponseMessage = "";
private static int serverResponseCode = 0;

public int uploadFile(final String sourceFileUri, final String serverFile) {

Debug.out("SourceFileUri: " + sourceFileUri);
Debug.out("ServerFile: " + serverFile);
Thread thread = new Thread() {
@Override
public void run() {
String upLoadServerUri = serverFile;
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
}
try { // open a URL connection to the Servlet
Debug.out("in the try");
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a
// HTTP
// connection
// to
// the
// URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
Debug.out("Set Properties and Datastream");
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Debug.out("Writes data");
bytesAvailable = fileInputStream.available(); // create a
// buffer of
// maximum
// size

bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
Debug.out("Buffer done");
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Debug.out("Read Bytes");
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
Debug.out("After sendData");
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
Debug.out("Server Response: " + serverResponseCode);
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
Debug.out("HTTP Response is : " + serverResponseMessage
+ ": " + serverResponseCode);
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
dialog.dismiss();
}

catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
// Toast.makeText(UploadImageDemo.this,
// "MalformedURLException", Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(),
ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
// Toast.makeText(UploadImageDemo.this, "Exception : " +
// e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}

}
};
thread.start();
try {
thread.join();
Debug.out("done uploading");
dialog.dismiss();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Debug.out("Message: " + serverResponseMessage.toString());
return serverResponseCode;
}

}

我在AsyncTask中调用该函数,因为我也需要做其他事情。我这样做是这样的:
private class MyAsyncTask extends AsyncTask<Mail, Integer, Double>{
/**
* Private boolean to check if a tire is repairable or not.</br>
*/
boolean _repairable = Step4._isRepairable;

/**
* Private integer which counts how many times we've tried to send the Email.
*/
private int _counter = 0;

private ProgressDialog dialog;

@Override
protected void onPreExecute(){
super.onPreExecute();
if(isPhotoTaken()){
ImageUploader uploader = new ImageUploader(_context);
uploader.uploadFile(getPhotoPath(), "http://obo.nl/android-upload-image.php");
}
}

/**
* Method used to start {@link #postData(Mail)} on a background thread.
*
* @return null
*/
@Override
protected Double doInBackground(Mail... params) {
postData(params[0]);
return null;
}

/**
* Method used to send the mail through a JSON Request in combination with the website.
* If there is no Internet connection the program will try to send the mail every 10 seconds.
*
* @param valueIWantToSend
*/
public void postData(Mail valueIWantToSend) {
if(AppStatus.haveNetworkConnection(_context)){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://obo.nl/android-mailing.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("from", valueIWantToSend.getFrom()));
nameValuePairs.add(new BasicNameValuePair("to", valueIWantToSend.getTo()));
nameValuePairs.add(new BasicNameValuePair("subject", valueIWantToSend.getSubject()));
nameValuePairs.add(new BasicNameValuePair("message", valueIWantToSend.getBody()));
nameValuePairs.add(new BasicNameValuePair("localized", getResources().getConfiguration().locale.getDisplayName()));
if(PathToPDF(_repairable).contains("Goed_Gekeurd_NL")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_BANDENANALYSE_GOED_GEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Afgekeurd_NL")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_BANDENANALYSE_AFGEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Goed_Gekeurd_FR")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_ANALYSEPNEUS_GOED_GEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Afgekeurd_FR")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_ANALYSEPNEUS_AFGEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Goed_Gekeurd_DE")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_REIFENANALYSE_GOED_GEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Afgekeurd_DE")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_REIFENANALYSE_AFGEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Goed_Gekeurd_EN")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_TYREANALYSE_GOED_GEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Afgekeurd_EN")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_TYREANALYSE_AFGEKEURD_PATH));
}
if(isPhotoTaken()){

//ImageUploader uploader = new ImageUploader(_context);
//uploader.uploadFile(getPhotoPath(),“ http://obo.nl/android-upload-image.php”);
nameValuePairs.add(new BasicNameValuePair(“photo”,getPhotoPath()));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler responseHandler = new BasicResponseHandler();
字符串响应= httpclient.execute(httppost,responseHandler);
                //This is the response from a php application
String reverseString = response;
Log.i("info", reverseString);

} catch (ClientProtocolException e) {

} catch (IOException e) {

}
} else {
if(_counter == 0){
_counter++;
_activity.runOnUiThread(new Runnable(){
public void run(){
Toast.makeText(_context, getString(R.string.noInternetEmailNotSend), Toast.LENGTH_LONG).show();
}
});

}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
postData(valueIWantToSend);
}
}

}

此外,_context在 Activity 的onCreate中设置如下:
_context = this;

在PostData方法中发生的事情是发送邮件,并将所拍摄的照片作为附件(但这并不是很有趣,因为它工作得很好)。

那么,对话框怎么不显示呢?

最佳答案

您没有在ImageUploader方法中启动线程。将您的方法更改为此:

public ImageUploader(Context ctx) {
this.context = ctx;
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
dialog = new ProgressDialog(context);
dialog.setCancelable(false);
dialog..setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Uploading Image... Please wait!");
dialog.show();
}
}).start();
}

关于android - 上载图片时,ProgressDialog不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19490469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com