サーバーに画像をアップロードするために使用されるクラスがあります。アップロード中に、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 アップローダー = new ImageUploader(_context); // uploader.uploadFile(getPhotoPath(), " http://obo.nl/android-upload-image.php "); nameValuePairs.add(new BasicNameValuePair("写真", getPhotoPath())); } httppost.setEntity(新しい 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 はアクティビティの onCreate で次のように設定されます。
_context = this;
PostData メソッドで行われるのは、撮影した写真を添付ファイルとしてメールを送信することです (ただし、これは非常にうまく機能するため、興味深いものではありません)。
では、なぜダイアログが表示されないのでしょうか?