I am uploading a file to my server using http post i have a simple method witch gets the job done but the loading…dialog never gets displayed how can i fix this … here is my code
public void send_data() throws IOException
{
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
ProgressDialog dialog = ProgressDialog.show(CaptureTestActivity.this, "",
"Loading. Please wait...", true);
dialog.show();
String urlServer = "http://poi.gps.ro:80/postimg?lat=" + String.valueOf(mDraw.lat) + "&lon=" + String.valueOf(mDraw.lon)+"&comment=" + tmp;
Log.w("DHA", urlServer);
URL url = new URL(urlServer);
if (url != null)
{
Log.w("DHA", "Merge aici");
connection = (HttpURLConnection) url.openConnection();
if (connection != null)
{
Log.w("DHA", "Si aici mere!");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "poi.gps.ro");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + "PICT0000" +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.write(btarr.toByteArray());
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
Log.w("DHA", "Incep trimiterea pozei!");
outputStream.flush();
outputStream.close();
int serverResponseCode = connection.getResponseCode();
String conn = connection.getResponseMessage();
// InputStream in = connection.getInputStream();
// StringWriter writer = new StringWriter();
Log.w("DHA", conn);
Log.w("DHA", "Serverul a raspuns cu " + String.valueOf(serverResponseCode));
if (serverResponseCode == 200)
{
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Super :)");
alertDialog.setMessage("Poza a fost trimisa cu success.");
alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
} });
alertDialog.show();
}
}
}
dialog.dismiss();
}
As David said, you need an AsynTask, most practical option. You can do some clever things with the Void, Void, Void part, but unless you want to look into the documentation, this should work fine.
And then when you call it, the cleanest way is to call
Also, I should mention, this should be an inner class, meaning don’t create a separate java file for it. Generally I just stick them at the bottom of the class file I’m working in.