Can someone tell me, why progressbar isnt showing when picture is being uploaded. I copied asynctask structure from my old project where it works. In my old project i use asynctask to download pictures from web server, and to show progressbar while downloading.
Here is my code:
public class PreviewPostActivity extends Activity {
ImageView imageView;
TextView tvComment;
Button submit;
MyLocationListener locationListener;
List<NameValuePair> list = new ArrayList<NameValuePair>();
private final String url = "***"; //Url of php script
ProgressDialog pDialog;
String responseMessage="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preview_post);
Intent intent = this.getIntent();
imageView = (ImageView)findViewById(R.id.imgPerview);
tvComment = (TextView)findViewById(R.id.txtPreviewComment);
submit = (Button)findViewById(R.id.btnPreviewSubmit);
Bitmap image = (Bitmap)intent.getParcelableExtra("picture");
String comment = intent.getStringExtra("comment");
locationListener = (MyLocationListener)intent.getSerializableExtra("location");
String imagePath = intent.getStringExtra("imagePath");
String date = intent.getStringExtra("date");
imageView.setImageBitmap(image);
tvComment.setText(comment);
//tvComment.append("\n"+locationListener.latitude + "\n"+locationListener.longitude);
list.add(new BasicNameValuePair("image", imagePath));
list.add(new BasicNameValuePair("comment", comment));
list.add(new BasicNameValuePair("longitude", Double.toString(locationListener.longitude)));
list.add(new BasicNameValuePair("latitude", Double.toString(locationListener.latitude)));
list.add(new BasicNameValuePair("date", date));
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new uploadPost().execute();
}
});
}
public void post(List<NameValuePair> nameValuePairs) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
HttpConnectionParams.setSoTimeout(httpParameters, 200000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity();
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File(nameValuePairs.get(index).getValue()),"image/jpeg"));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity httpEntity = response.getEntity();
String responseMessage = EntityUtils.toString(httpEntity);
tvComment.setText(responseMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
class uploadPost extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PreviewPostActivity.this);
pDialog.setMessage("Uploading post. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
//post(list);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
HttpConnectionParams.setSoTimeout(httpParameters, 200000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity();
for(int index=0; index < list.size(); index++) {
if(list.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(list.get(index).getName(), new FileBody(new File(list.get(index).getValue()),"image/jpeg"));
} else {
// Normal string data
entity.addPart(list.get(index).getName(), new StringBody(list.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity httpEntity = response.getEntity();
responseMessage = EntityUtils.toString(httpEntity);
//tvComment.setText(responseMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
tvComment.setText(responseMessage);
pDialog.dismiss();
}
}
So when i hit button for upload, screen freezes and stay frozen until upload is complete, and progress bar isnt showing at all. Sometimes it shows, but its rly rear and i dont know why. I have tried calling Post() method from class in doInBackground body insted of whole code (code in body is the same as in post() method) but effect is the same, so i guess i didnt do something right in creating progressbar. But again i say i copied whole asynctask code from old project in witch it worked fine.
EDIT:
I just tryed creating progress bar in constructor of PreviewPostActivity.class and after that i made constructor for asynctask class but it still dosent work. I am rly confused becouse it worked in my old program.
Here is code from him:
class GetSlike extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(KlubSlikeActivity.this);
pDialog.setMessage("Ucitavanje u toku. Molimo vas sacekajte...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
String id = Integer.toString(k.getId());
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("klub",id));
slikeUrl = JSONAdapter.getSlike(params);
gv.setAdapter(new SlikeAdapter(slikeUrl,KlubSlikeActivity.this));
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
Only thing changed is doInBackground body...
Edited:
Dialog is display after runOnUiThread() is executed.
I found this library which is perfect to accomplish the upload task and also provide a progress handler which could be used to set the value of a ProgressBar:
https://github.com/nadam/android-async-http
It could be used like the following... Set onClickHandler for the upload Button:
#Override
public void onClick(View arg0) {
try {
String url = Uri.parse("YOUR UPLOAD URL GOES HERE")
.buildUpon()
.appendQueryParameter("SOME PARAMETER IF NEEDED 01", "VALUE 01")
.appendQueryParameter("SOME PARAMETER IF NEEDED 02", "VALUE 02")
.build().toString();
AsyncHttpResponseHandler httpResponseHandler = createHTTPResponseHandler();
RequestParams params = new RequestParams();
// this path could be retrieved from library or camera
String imageFilePath = "/storage/sdcard/DCIM/Camera/IMG.jpg";
params.put("data", new File(imageFilePath));
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, httpResponseHandler);
} catch (IOException e) {
e.printStackTrace();
}
}
then add this method to your activity code:
public AsyncHttpResponseHandler createHTTPResponseHandler() {
AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
}
#Override
public void onProgress(int position, int length) {
super.onProgress(position, length);
progressBar.setProgress(position);
progressBar.setMax(length);
}
#Override
public void onSuccess(String content) {
super.onSuccess(content);
}
#Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
}
#Override
public void onFinish() {
super.onFinish();
}
};
return handler;
}
Run on ui thread in asynctask doinbackground() is not correct. Also you are returning null in doInBackground() and you have parameter file_url in onPostExecute(). Return value in doInbackground() recieve value in onPostExecute().
doInBackGround() runs in background so you cannot access or update ui here.
To update ui you can use onPostExecute().
Your AsyncTask should be something like below. You are doing it the wrong way.
http://developer.android.com/reference/android/os/AsyncTask.html. See the topic under The 4 steps
pd= new ProgressDialog(this);
pd.setTitle("Posting data");
new PostTask().execute();
private class PostTask extends AsyncTask<VOid, Void, Void> {
protected void onPreExecute()
{//display dialog.
pd.show();
}
protected SoapObject doInBackground(Void... params) {
// TODO Auto-generated method stub
//post request. do not update ui here. runs in background
return null;
}
protected void onPostExecute(Void param)
{
pd.dismiss();
//update ui here
}
Related
I want to upload multiple image files using Android MultiPart Entity via AsyncTask in an activity. When I attempt to upload single image file then the progress dialog shows correct progress and as soon as 100% progress is reached the dialog dismisses and does the further tasks. But, when I am attempting to upload multiple image files it shows the 100% progress and the progress dialog is stuck till other image files are being uploaded to server. I add the multiple image files to entity using a for loop. But when I try to get the content length it seems that I am getting wrong value.
#SuppressWarnings("deprecation")
private class UploadAttachments extends AsyncTask<Void, Integer, String> {
ProgressDialog pDialog;
long totalSize = 0;
int statusCode;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegistrationActivity.this);
pDialog.setMessage(getString(R.string.label_upload_attachments));
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setMax(mFilePaths.size());
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
pDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Network.URL_UPLOAD);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
for (int i = 0; i < mFilePaths.size(); i++) {
entity.addPart("image" + i, new FileBody(new File(mFilePaths.get(i))));
mPrefix += 1;
entity.addPart("prefix" + i, new StringBody(String.valueOf(mPrefix)));
}
totalSize = entity.getContentLength();
entity.addPart("count", new StringBody(String.valueOf(mFilePaths.size())));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = getString(R.string.label_upload_successful);
} else {
responseString = getString(R.string.error_network_error);
}
} catch (IOException e) {
responseString = getString(R.string.error_network_error);
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if (mToast != null) mToast.cancel();
mToast = makeText(getApplicationContext(), result, Toast.LENGTH_SHORT);
mToast.show();
mPreferences.clearRegDetails();
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
}
}
Please have a look. Please help me on this! Thanks.
I am trying to setup Progress Bar to getting large amount of JSON from Server by showing percentage but it not working.I have don't idea regarding this.So Please help me from scratch.
Test.java
public class Test extends AppCompatActivity {
// Progress Dialog
private ProgressDialog pDialog;
private Toolbar mToolbar;
public static final int progress_bar_type = 0;
List<NameValuePair> params;
// File url to download
private static String file_url = "http://dcntv.in:3035/area_list";
Connect cn = new Connect();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("opid", "19"));
new DownloadFileFromURL().execute(file_url);
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String...urls) {
return cn.readJSONFeed(urls[0],params);
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String result) {
Dialog d = new Dialog(Test.this);
TextView tv = new TextView(Test.this);
tv.setText(result.toString());
ScrollView sv = new ScrollView(Test.this);
sv.addView(tv);
d.setContentView(sv);
d.show();
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
}
Connect.java (for cn Object)
public class Connect {
public String readJSONFeed(String URL,List<NameValuePair> params) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
}
return stringBuilder.toString();
}
}
Progress Bar popup but progress count not working
Because not calling publishProgress method from doInBackground to publish progress update on UI Thread.
Publish update using current code make following changes:
1. Add one more parameter in readJSONFeed to get object of DownloadFileFromURL :
public String readJSONFeed(String URL,List<NameValuePair> params,
DownloadFileFromURL objDownloadFileFromURL) {
... ...
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
// add this line
objDownloadFileFromURL.publishProgress(stringBuilder.length());
}
....
}
2. Pass DownloadFileFromURL.this when calling readJSONFeed from doInBackground :
return cn.readJSONFeed(urls[0],params,DownloadFileFromURL.this);
I have multiple images and i am uploading on php server using asynctask my problem is i want to show circular progress bar on every image individually like whatsapp but don't know how to do. here is my code
/**
* Uploading the file to server
* */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected String doInBackground(Void... params)
{
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(serviceurl+"conversations.php");
try {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
/* example for setting a HttpMultipartMode */
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File sourceFile = new File(imgDecodableString);
// Progress listener - updates task's progress
MyHttpEntity.ProgressListener progressListener =
new MyHttpEntity.ProgressListener() {
#Override
public void transferred(float progress) {
publishProgress((int) progress);
}
};
// Adding file data to http body
entity.addPart("file", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addTextBody("from_user",(prefid.getString("userid", null)),ContentType.TEXT_PLAIN);
entity.addTextBody("to_user",touser_id,ContentType.TEXT_PLAIN);
entity.addTextBody("message_type", msg_type,ContentType.TEXT_PLAIN);
httppost.setEntity(new MyHttpEntity(entity.build(),
progressListener));
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
I am calling above code in my main activity and i am using this to upload images and video.
please help me how i can set progress bar on multiple images same as in whatsapp
Thanks
You could pass the View to the AsyncTask, by create new constructor then show/hide it, notice that you have to runOnUIThread for the view.
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
ImageView iv_loading;
public UploadFileToServer(ImageView iv_loading){
this.iv_loading = iv_loading;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
runOnUiThread(new Runnable() {
#Override
public void run() {
iv_loading.setVisibility(View.VISIBLE);
}
}
);
}
...
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv_loading.setVisibility(View.GONE);
}
}
);
}
}
I googled for hours and tried all answers of Stack Overflow but didn't solved my problem.
I made android program to download data in bytes which wroks perfectly. And for download working on background thread. I want to show a Progress Dialog(jus Spinning one). But I'm having really annoying problem. My download takes about 5 sec but my progress dialog is either not shown or just shown for last 1 sec.
Here's my code for AsyncTask.
public class ImageJSON extends AsyncTask<String, String, byte[]> {
private JSONObject jsonObject = new JSONObject();
private byte[] response;
private ProgressDialog pg;
private Context context;
public ImageJSON(Activity activity) {
pg = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pg.setMessage("Downloading, please wait.");
pg.show();
}
#Override
protected void onProgressUpdate(String... progress) {
super.onProgressUpdate(progress);
if (pg != null) {
pg.setProgress(Integer.parseInt(progress[0]));
}
}
protected void onPostExecute(byte[] result) {
if (pg.isShowing()) {
pg.dismiss();
}
}
#Override
protected byte[] doInBackground(String... params) {
HttpPost httpPost = new HttpPost("my file url....");
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
try {
jsonObject.put("imageId", params[0]);
StringEntity stringEntity = new StringEntity(jsonObject.toString());
httpPost.addHeader("Content_Type", "application/octet_stream");
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost, httpContext);
HttpEntity entity = httpResponse.getEntity();
if (entity!=null) {
response = EntityUtils.toByteArray(entity);
entity.consumeContent();
httpClient.getConnectionManager().shutdown();
}
} catch (JSONException|IOException e) {
e.printStackTrace();
}
return response;
}
And I called it from my activity using this code.
final ImageJSON imageTask = new ImageJSON(ReaderActivity.this);
byte[] response = imageTask.execute(imageId).get();
If anybody can help me, Thanks in advance.
You don't want to be using get() as it still freezes your UI thread thus denying the sense of using AsyncTask. You might want to implement onPostExecute in order to return your result properly.
try this -
public ImageJSON(Activity activity) {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(ReaderActivity.this);
pg.setMessage("Downloading, please wait.");
pg.show();
}
you forgot to initilise your progressDialogue in onPreExecute method
#Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(pass_context_here);
pg.setMessage("Downloading, please wait.");
pg.show();
}
Change this
public ImageJSON(Context ctx) {
this.context = ctx;
}
Now in your onPreExecute() method use this
#Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(context);
pg.setMessage("Downloading, please wait.");
pg.show();
}
You'r initializing your ProgressDialog in ImageJSON class which block your UI thread means freezes it. So need to initialize it in onPreExecute() method with reference of context.
I'm developing an Android app. I want to post to a server using asynctask. However, I still have an error which indicates that the UI thread is blocked.
I want to parse the XML response and display it in a list view, but I cannot proceed because the UI thread is still blocked.
public class AsynchronousPost extends ListActivity implements OnClickListener {
EditText SearchValue;
Button SearchBtn;
String URL = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_interface);
SearchBtn = (Button) findViewById(R.id.searchbtn);
SearchBtn.setOnClickListener(this);
}
public void onClick(View views) {
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Integer, Document> {
private final String URL = "url";
private final String username = "username";
private final String password = "password";
private EditText SearchValue;
#Override
protected Document doInBackground(String... arg0) {
// TODO Auto-generated method stub
getXmlFromUrl(URL); // getting XML
return null;
}
#Override
protected void onPostExecute() {
//want to parse xml response
//display on listview
}
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
SearchValue = (EditText) findViewById(R.id.search_item);
String Schvalue = SearchValue.getText().toString();
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
5);
nameValuePairs
.add(new BasicNameValuePair("username", username));
nameValuePairs
.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("searchItem",
Schvalue));
// response stored in response var
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
// return XML
return xml;
}
}
}
There are a couple problems that I see. First, you aren't passing anything in execute() but in your class declaration you are telling doInBackground() to expect a String. Secondly, you are telling onPostExecute() to expect a Document but you are returning null from doInBackground() and not taking any parameters in onPostExecute(). Unless I missed something, I don't see how this even compiles
protected Object doInBackground(String... params) {
//this method of AsyncTask is not running on the UI Thread -- here do just non UI taks
return result;
}
#Override
protected void onPostExecute(Object result) {
//I'm not sure but I think this method is running on the UI Thread
//If you have long operations here to do you will block UI Thread
//put the tasks in the doInBackground...
//to fill the elements in the UI elements use
//
runOnUiThread (new Runnable() {
#Override
public void run() {
//here fill your UI elements
}});
}