Progress notifications from AndroidHttpClient - android

I am working with Android 3.0 and 3.1.
I use the class AndroidHttpClient in my application and for the execute I use execute(HttpUriRequest).
I have a progress bar in the UI that I want to be updated while sending data.
Is there any way to get notifications from the AndroidHttpClient about the progress of the data sending (I guess it doesn't send the whole buffer in one shot)?
Thanks

To track the progress of data as it is sent to the server you have to wrap the underlying HTTP entity that is being sent. If you subclass HttpEntityWrapper and override writeTo() you can wrapper the OutputStream with a FilterOutputStream that is the stream being written to the server.

i think you need AsyncTask example , may be it will help you ::
private class xyz extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(tranning.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please Wait...");
this.dialog.show();
// put your code which preload with processDialog
}
#Override
protected Void doInBackground(Void... arg0) {
// put you code here
return null;
}
#Override
protected void onPostExecute(final Void unused) {
//if (this.dialog.isShowing()) {
// this.dialog.dismiss();
//}
}
}
and use it in your main class ::
new xyz().execute();

Related

Asynchronous task is executed 2 times because of the poor quality of the internet-

I have an asynchronous task in Android Studio, to send and receive data from a server as follows.
private class myTask extends AsyncTask<Void, Void, Integer> {
Exception excepccion;
protected void onPreExecute() {
super.onPreExecute();
Mensaje.mensajeConectandoseSicoy(actMetodoPago,getString(R.string.msg_conexion_sicoy));
}
#Override
protected Integer doInBackground(Void... params) {
try {
return new Servidor().guardarObtnerInfoServidorSicoy(ACCION_PAGAR_PEDIDO);
} catch (Exception e2) {
excepccion = e2;
return -1;
}
}
#Override
protected void onPostExecute(Integer respuesta) {
Mensaje.detenerMensajeConectandoseSicoy();
...
}
Where:
public static void mensajeConectandoseSicoy(Context context, String mensaje){
pd = new ProgressDialog(context);
pd.setMessage(mensaje);
pd.setCancelable(false);
Handler pdCanceller = new Handler();
pd.show();
}
public static void detenerMensajeConectandoseSicoy(){
if (pd.isShowing()){
pd.dismiss();
}
}
This process works very well until a user reported problems and discovered that their internet is of very poor quality.
When the task is running onPostExecute, that is, when the server has already responded, it is again executed onPreExecute, and this triggers a series of errors.
I solved it by putting a Boolean type flag variable, to avoid the problem.
My question is:
Is there a way to do that control in a better way?

How can i cancel the AsynsTask in Android?

Hi onCancel of dialog i want to cancel to server call but i m facing problem that even i cancel the task, it hits my server and modifies the data. How can I resolve this issue ? Below is my code..
private class UserBoardingTask extends AsyncTask {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage(getResources().getString(R.string.please_wait));
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (userOnBoardingTask!= null && userOnBoardingTask.getStatus() != AsyncTask.Status.FINISHED && !userOnBoardingTask.isCancelled()) {
userOnBoardingTask.cancel(true);
}
}
});
progressDialog.show();
}
#Override
protected Void doInBackground(String... urls) {
String boardingURL=null;
boardingURL= getUrl();
UserOnBoardingDTO userOnBoardingDetailsDTO = AppStateManager.getUserBoardingDetails();
try{
RestAPIManager.putToNSWebService(boardingURL, userOnBoardingDetailsDTO, username, password);
}
catch (Exception e) {
errorMessage=getResources().getString(R.string.unknown_exp);
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
closeProgressDialog();
errorMessage="";
AppStateManager.setUserBoardingDetails(null);
userOnBoardingTask=null;
}
#Override
protected void onPostExecute(Void res) {
closeProgressDialog();
userOnBoardingTask=null;
if(!FieldsValidator.isBlank(errorMessage)){
CommonUtil.showToast(getActivity(),errorMessage);
errorMessage="";
return;
}
Just check isCancelled() once in a while:
protected Object doInBackground(Object... x) {
while (/* condition */) {
// work...
if (isCancelled()) break;
}
return null;
}
and another solution is
protected void onProgressUpdate(String... progress1) {
if(condition){
break;
}
}
Move the dialog out of the async task and only start the task when the dialog is not canceled.
Actually the problem is not termination of your asynsTask but the server hit if a server hit is already done before termination of asynsTask then you must interrupt your server request also.Just terminate your server request using abort method.
Where is userOnBoardingTask declared and where it is assigned to a reference to running task? I suspect this does not store a proper reference when the task tries to cancel it.
I am not sure if it is the actual reason of your problem. But for sure you may get rid of this variable if it is intended to pint at current task. Just change dialog's on cancel listener:
private class UserBoardingTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
// ...
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (UserBoardingTask.this.getStatus() != AsyncTask.Status.FINISHED
&& UserBoardingTask.this.isCancelled()) {
UserBoardingTask.this.cancel(true);
}
}
});
In fact you may omit UserBoardingTask.this phrase as the inner class can point directly fields of nesting class as far as the names are not obscured by the names of inner class members:
private class UserBoardingTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
// ...
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (getStatus() != AsyncTask.Status.FINISHED && isCancelled()) {
cancel(true);
}
}
});
EDIT
Another point is that before sending request to the server you may check inside doInBackground you may check if the task has not been cancelled
// ...
#Override
protected Void doInBackground(String... urls) {
// ...
try {
if(isCancelled()) {
throw new Exception("Exit: task cancelled!");
}
RestAPIManager.putToNSWebService(boardingURL, userOnBoardingDetailsDTO, username, password);
// ...
RestAPIManager.putToNSWebService(boardingURL, userOnBoardingDetailsDTO, username, password);
This above code hit the server. So you have to validate the execution of code inbetween cancellation.
Try something like this
try{
if(!userOnBoardingTask.isCancelled())
{
RestAPIManager.putToNSWebService(boardingURL, userOnBoardingDetailsDTO, username, password);
}
}
catch (Exception e) {
errorMessage=getResources().getString(R.string.unknown_exp);
}
This is ok. If user cancel the task before ResetAPIManager code executes. Suppose user try to cancel the task after server call initiated you have to tell already modified or remodify server data or unable to cancel or some message to user. All done through getting server reponse and validate server response if it changed or not.
Use something like this
Var rsponse = RestAPIManager.putToNSWebService(boardingURL,userOnBoardingDetailsDTO, username, password);
Validate the reponse message in onPostExecute() or OnCancelled() method.
If you cancel the asynctask after access this method
RestAPIManager.putToNSWebService(boardingURL,userOnBoardingDetailsDTO, username, password); the async task will cancel after running the above code so you should correct this by creating a new method inside RestAPIManager class and call that method inside OnCancelled method from your asyncTask.
Short Anser: Its not possible stop data posts thru a simple cancel. once an async task runs even if you cancel it mid way data posts will occure. Cancellation can be done in a Simple Run
Check this Post
[Android - Cancel AsyncTask Forcefully

How can i send mulltiple images at once to server?

i need to send three images at once to server, currently i can send one image by following code(PictureId). If i need to send three images say Picture1Id, Picture2Id, Picture3Id how can set in (protected Void doInBackground(Void... params) {})
// IMAGE UPLOAD ///////////
final ProgressDialog progress = new ProgressDialog(NBCompetitorTracking_Activity.this);
progress.setMessage("Uploading image, please wait...");
// If auto upload true upload picture:
if (new SessionManager(NBCompetitorTracking_Activity.this).isAutoUpload()) {
// upload image
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.show();
}
#Override
protected Void doInBackground(Void... params) {
UploadImage.uploadImage(NB_CompetitorTracking.**PictureId**);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progress.dismiss();
}
};
}
// END: IMAGE UPLOAD ///////////
Start multiple Thread instances of the 'upload thread' with separate files to be uploaded.Purely upon java concept, You can write a Thread class that uploads a file. And initiate many instances(as much as the files) and start them all together.

How to close parent thread on Android

I would like to do step by step upload date to web service.
My code:
private Thread WebServiceThread;
public void onCreate(Bundle savedInstanceState) {
//...
WebServiceThread = new WebService();
WebServiceThread.start();
}
private class WebService extends Thread {
public void run() {
try {
new WebServiceUpload().execute("");
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}
}
private class WebServiceUpload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... data) {
// upload part
}
protected void onPostExecute(String result) {
//...
WebServiceThread = new WebService();
WebServiceThread.start();
//<Tab>__what to do here__</Tab>
//...
}
}
Now can run, but cause the device slow.
Please tell me how to close parent thread or restart parent thread way to solve this problem. (or other practice to same target.)
You don't have to chain threads like that. Just create a single AsyncTask extension that uploads the data step by step in doInBackground. If you want to publish progress reports, you can do that by calling publishProgress.
Your method of creating a WebServiceUpload from a worker thread is really bizarre and will most likely not work. AsyncTask is designed to be started from the UI thread. Just call your new WebServiceUpload().execute() from the main thread when you want to start the upload steps.
In your onPostExecute check if thread is running then force it to stop.
protected void onPostExecute(String result) {
//...
**if (WebServiceThread.isAlive())
WebServiceThread.stop();**
WebServiceThread = new WebService();
WebServiceThread.start();
//<Tab>__what to do here__</Tab>
//...
}

Android async task download failed err

I've developed an application that takes content from the internet and shows it accordingly on the device's screen . The program works just fine , a little bit slow . It takes about 3-4 seconds to load and display the content . I would like to put my code that does all the work ( grabbing web content and displaying it) in a background thread . Also , I'd like to show a progress dialog .
public class Activity1 extends Activity
{
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncTask<Integer, Integer, Boolean>()
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(Activity1.this, "",
"Loading...");
}
#Override
protected Boolean doInBackground(Integer... params)
{
if (params == null)
{
return false;
}
try
{
/*
* This is run on a background thread, so we can sleep here
* or do whatever we want without blocking UI thread. A more
* advanced use would download chunks of fixed size and call
* publishProgress();
*/
Thread.sleep(params[0]);
// HERE I'VE PUT ALL THE FUNCTIONS THAT WORK FOR ME
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
/*
* The task failed
*/
return false;
}
/*
* The task succeeded
*/
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
/*
* Update here your view objects with content from download. It
* is save to dismiss dialogs, update views, etc., since we are
* working on UI thread.
*/
AlertDialog.Builder b = new AlertDialog.Builder(Activity1.this);
b.setTitle(android.R.string.dialog_alert_title);
if (result)
{
b.setMessage("Download succeeded");
}
else
{
b.setMessage("Download failed");
}
b.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dlg, int arg1)
{
dlg.dismiss();
}
});
b.create().show();
}
}.execute(2000);
/* new Thread()
{
#Override
public void run()
{
// dismiss the progressdialog
progressDialog.dismiss();
}
}.start();
}*/
}
If I run the application with this code , I get this : download failed . On the other hand , if I keep the final thread , the app crashes , NullPointerException . I really don't know what to do anymore .
I would really appreaciate if you could give me an alternative to this code , not just some hints because I'm new to android and I really don't know much . Thanks.
UPDATE :
I don't want to display the progress of the download , I want to display the progress dialog until the app is ready to display the full content.
The best approach to do this is by using the AsyncTask class, as it will allow you to execute some background process and update the UI at the same time (in your case, it's a progress bar).
This is an example code:
ProgressDialog mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("the url to the file you want to download");
The AsyncTask will look like this:
private class DownloadFile extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL(url[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.ext");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
The method above (doInBackground) runs always on a background thread. You shouldn't do any UI tasks there. On the other hand, the onProgressUpdate runs on the UI thread, so there you will change the progress bar:
#Override
public void onProgressUpdate(String... args){
// here you will have to update the progressbar
// with something like
mProgressDialog.setProgress(args[0]);
}
}
You will also want to override the onPostExecute method if you want to execute some code once the file has been downloaded completely.
You should create an inner class for AsyncTask like this :
private class YourTask extends AsyncTask<Context, Void, Void>
{
ProgressDialog dialog = new ProgressDialog(mContext);
protected void onPreExecute()
{
dialog.setMessage("loading..");
dialog.show();
}
protected Void doInBackground(Context... params)
{
// ...
return null;
}
protected void onPostExecute(final Void unused)
{
dialog.dismiss();
}
}
and in onCreate() put :
new YourTask().execute();
and for more detail you should check this once:
http://developer.android.com/reference/android/os/AsyncTask.html
When you use the new thread, your app crashes because the progress dialog is not initialized there
Inside your new thread use:
`progressDialog = ProgressDialog.show(Activity1.this, "","Loading...");
and about that alert dialog: Basically either params is null or the logic is throwing some exception. It's not returning true
so check the ddms logs and post them here.
`

Categories

Resources