No Progress Bar update...Async - android

I'm simply loading an image on button click via url , i want progress bar to show downloadin done,0-100 now i had changed the code not showing the progress updation but only progress bar
kindly help. XML has a button [downloadbtn], and a progressbar, imageview and a quit button
mainfest.xml has acsess permission internet
code:
*
package com.example.t4;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ProgressBar prgs;
ProgressTask task = new ProgressTask();
Button showProgressBtn;
Button stopProgressBtn;
ImageView img;
Bitmap bmp ;
TextView tv1;
int filesize,filedyn;
public void startdownload(){
try { URL url;
url = new URL("http://whywedoit.files.wordpress.com/2009/04/smile.jpg");
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
filesize = urlConnection.getContentLength();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.tv1);
img = (ImageView) findViewById(R.id.imageView1) ;
stopProgressBtn = (Button) findViewById(R.id.btnCancel);
prgs = (ProgressBar) findViewById(R.id.progress);
showProgressBtn = (Button) findViewById(R.id.btn);
prgs.setVisibility(View.INVISIBLE);
img.setVisibility(View.INVISIBLE);
tv1.setVisibility(View.INVISIBLE);
final ProgressTask pgt = new ProgressTask();
showProgressBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(pgt.getStatus()==Status.RUNNING){Toast.makeText(getApplicationContext(), "Status"+pgt.getStatus(), Toast.LENGTH_SHORT).show();}
if(pgt.getStatus()==Status.FINISHED||pgt.getStatus()==Status.PENDING){
Toast.makeText(getApplicationContext(), "Status"+pgt.getStatus(), Toast.LENGTH_SHORT).show();
prgs.setVisibility(View.VISIBLE);
task.execute(10);
tv1.setVisibility(View.VISIBLE);
}}
});
stopProgressBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
stopProgress();
}
});
}
private class ProgressTask extends AsyncTask<Integer,Integer,Void>{
protected void onPreExecute() {
super.onPreExecute();
prgs.setMax(100); // set maximum progress to 100.
}
protected void onCancelled() {
prgs.setMax(0); // stop the progress
Log.v("Progress","Cancelled");
finish();
}
protected Void doInBackground(Integer... params) {
startdownload();
//for(int j=0;j<=filesize;j++){
publishProgress((int) ((filedyn / (float) filesize) * 100));
//}
Log.v("Progress","Downloading");
return null;
}
protected void onProgressUpdate(Integer... values) {
prgs.setProgress(0);
Log.v("Progress","Updating");
}
protected void onPostExecute(Void result) {
img.setVisibility(View.VISIBLE);
tv1.setVisibility(View.INVISIBLE);
img.setImageBitmap(bmp);
prgs.setVisibility(View.INVISIBLE);
Log.v("Progress", "Finished");
}
}
public void stopProgress() {
task.cancel(true);
}
}
*

Sorry, I don't think you only have progress bar update problems. There are too many points needs to be repaired.
1st inside your OnClickListener, you are doing task.execute(10);showProgress(); AsnycTask is asynchronous task, you cannot put your showProgress() there. Do something with your code.
private boolean init = true;
private Void doInBackground(Integer... params) {
init = true;
startdownload();
Log.v("Progress", "Downloading");
return null;
}
protected void onProgressUpdate(Integer... values) {
if (init){
showProgress();
init = false;
}else{
prgs.setProgress(5);
Log.v("Progress", "Once");
}
}
2nd startdownload method, are you sure your startdownload method doing downloading? or just getting the length of filesize. Make it clear else you will get yourself confuse.
3nd To invoke onProgressUpdate, you need to call publishProgress(progressValue); Here's the sample.
private Void doInBackground(Integer... params) {
init = true;
startdownload();
publishProgress(5); // onProgressUpdate invoked
//
// doing download
//
Log.v("Progress", "Downloading");
return null;
}

use this code and use progressdialog instead of progressbar
#Override
protected void onProgressUpdate(Integer... progress) {
//Set the pertange done in the progress dialog
pd.setProgress((int) (progress[0]));
}

You need set the ProgressBar max value and you need to update the progress in onProgressUpdate
protected void onProgressUpdate(Integer... values) {
prgs.setProgress(values[0]);
Log.v("Progress","Once");
}
and call
publishProgress(progress)
in the doInBackground of ProgressTask to update the progress
Check for more ref

Related

Progress dialog box not showing in global AsyncTask class

This is my MainActivity... i put one button, in button onclick i call asyncTask
package com.example.asnytaskpro;
import java.util.concurrent.ExecutionException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AsyncMainActivity extends Activity implements OnClickListener {
Button button ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_async, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.err.println("1");
try {
new AllPrinterClass(AsyncMainActivity.this, "123456789123456789", "123").execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
}
This is My AsyncTaskClass
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.widget.Toast;
public class AllPrinterClass extends AsyncTask<Integer, Integer, Integer>{
public static String ServerData = "";
private ProgressDialog prgDialog;
private Context context;
String TransNo = "" ,IMEINo = "";
int iRetValue = 0;
String CurrentDate = null, CurrentTime= null;
SimpleDateFormat df,tf;
public AllPrinterClass(Context context1, String imeiNo,String transno2)
{
this.context = context1;
this.IMEINo = imeiNo;
this.TransNo = transno2;
Calendar c = Calendar.getInstance();
df = new SimpleDateFormat("dd/M/yyyy");
CurrentDate = df.format(c.getTime());
tf = new SimpleDateFormat("hh:mm:ss");
CurrentTime = tf.format(c.getTime());
System.err.println(CurrentDate);
System.err.println(CurrentTime);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.prgDialog = new ProgressDialog(context);
this.prgDialog.setMessage("Place your finger on FPS ...");
this.prgDialog.setIndeterminate(true);
this.prgDialog.setCancelable(false);
this.prgDialog.show();
}
#Override
protected Integer doInBackground(Integer... params) {
//////////////////Doing my Code///////////////////
for (int i = 0; i < 10; i++) {
System.err.println("i :-" + i);
SystemClock.sleep(500);
}
/////////////////////////////////////////////////////
return iRetValue;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
prgDialog.dismiss();
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
}
}
This code working for me but my ProgressDialog not showing(May be run background).
In i remove prgDialog.dismiss(); in onPostExecute() Method then my dialog showing after doInBackground() Method.
I want dialog show in onPreExecute() Method and dismiss in onPostExecute() method.
Here:
...execute().get();
Calling get method will block main ui Thread until doInBackground execution not completed. that's why ProgressDialog is not showing.
Use only execute() method to start AsyncTask which show Progress Dialog during doInBackground method execution:
new AllPrinterClass(AsyncMainActivity.this,
"123456789123456789", "123").execute();

OnclickListener force closes. not sure if its in the right place

ok so i have a template that installs an apk from the assets folder. recently ive been modding the template to accomodate features that i wanted to add, so im basically adding to code that was there already.
ive added 2 onclicklisteners and both of them fail with the error "No activity found to handle the intent"
heres what i have
package com.example.depthtiles;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.example.depthtiles.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.Toast;
public class MainActivity extends Activity {
// change this to your apk skin name
private static final String ZOOPER_APK = "Depth Zooper.apk";
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
context = this;
setContentView(R.layout.activity_main);
ScrollView sView = (ScrollView)findViewById(R.id.ScrollView02);
//Hide the Scrollbar
sView.setVerticalScrollBarEnabled(false);
sView.setHorizontalScrollBarEnabled(false);
findViewById(R.id.InstallSkinButton).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
showInstallableSkins();
}
});
findViewById(R.id.InstallIconButton).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.example.depthfinal.ICONBUTTON"));
}
});
findViewById(R.id.ButtonGmail).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.example.depthfinal.CONTACTGMAIL"));
}
});
}
private class RepairSkinAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog mDialog;
#Override
protected void onPreExecute() {
mDialog = ProgressDialog.show(context, "", "Processing...", true);
}
#Override
protected Void doInBackground(Void... nothing) {
String SDCARD_MYAPK_APK = Environment.getExternalStorageDirectory()
.getPath() + File.separator + "my_temporary_skin_apk.apk";
deleteOldSkin(SDCARD_MYAPK_APK);
saveSkinToSdCard(SDCARD_MYAPK_APK);
startAppInstaller(SDCARD_MYAPK_APK);
return null;
}
#Override
protected void onPostExecute(Void result) {
mDialog.dismiss();
finish();
}
}
/**
*
*/
private void showInstallableSkins() {
if (isSDcardAvailable()) {
new RepairSkinAsyncTask().execute();
} else {
Toast.makeText(this, "SD card not available", Toast.LENGTH_LONG)
.show();
}
}
private void deleteOldSkin(String pathToSkin) {
File file = new File(pathToSkin);
if (file.exists()) {
file.delete();
}
}
/**
* #param assetManager
* #param in
* #param out
* #param pathToSkin
*/
private void saveSkinToSdCard(String pathToSkin) {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(ZOOPER_APK);
try {
out = new FileOutputStream(pathToSkin);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* #param pathToSkin
*/
private void startAppInstaller(String pathToSkin) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(pathToSkin)),
"application/vnd.android.package-archive");
startActivity(intent);
}
private boolean isSDcardAvailable() {
String state = Environment.getExternalStorageState();
return state.contentEquals(Environment.MEDIA_MOUNTED)
|| state.contentEquals(Environment.MEDIA_MOUNTED_READ_ONLY);
}
}
the first onclick was there from the template and works fine. the 2 that i added however do not. Im just starting out in android and im not sure if there in the right spot.
Try this..
Change this
startActivity(new Intent("com.example.depthfinal.ICONBUTTON"));
startActivity(new Intent("com.example.depthfinal.CONTACTGMAIL"));
to
startActivity(new Intent(MainActivity.this,ICONBUTTON.class));
startActivity(new Intent(MainActivity.this,CONTACTGMAIL.class));
Inside Click
findViewById(R.id.InstallIconButton).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(MainActivity.this,ICONBUTTON.class));
}
});
You can either initialise Button first like this
Button btn=(Button)findViewById(R.id.btn_st_open2);
then set listner on it like this
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// do something you want
}
});
or in your code just do casting at The OnclickListner part like this
(Button)findViewById(R.id.InstallSkinButton).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
showInstallableSkins();
}
});
hopefully it will help you thanks

Async task wont stop

package com.example.asynctask;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
ProgressBar progressbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressbar = (ProgressBar) findViewById(R.id.progressBar);
}
class ProgressTask extends AsyncTask<Integer, Integer, Void> {
private boolean flag = true;
#Override
protected void onPreExecute() {
progressbar.setMax(100);
}
#Override
protected void onCancelled() {
//progressbar.setMax(0);
flag = false;
Log.v("onCancelled:flag", String.valueOf(flag));
}
#Override
protected Void doInBackground(Integer... params) {
// TODO Auto-generated method stub
int start = params[0];
for (int i = start; i <= 100; i=i+10) {
if (!flag) {
break;
} else {
publishProgress(i);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("ThreadError", e.toString());
}
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
progressbar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
Log.v("Progress", "Finish");
}
}
public void onClick(View v) {
ProgressTask task = new ProgressTask();
switch (v.getId()) {
case R.id.start:
task.execute(10);
break;
case R.id.stop:
task.cancel(true);
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here is a symple AsyncTask app which starts to update the progress bar when you hit Start. But when you will hit stop, it wont stop. Thing is when you call task.cancel(true), onCancelled() methods does gets invoked and changes the value of flag to false but in onCancelled() value of flag remains true. I have also tried isCancelled() in place of flag varaible with no success. For a moment my problem is similar to Ollie C, but no exceptions are thrown in my case.
As Wenhui pointed out in the comment, I made a silly mistake in which I declared and instantiated task inside onClick(View v).

using AsyncTask class for parallel operationand displaying a progress bar

I am displaying a progress bar using Async task class and simulatneously in parallel operation , i want to retrieve a string array from a function of another class that takes some time to return the string array.
The problem is that when i place the function call in doing backgroung function of AsyncTask class , it gives an error in Doing Background and gives the message as cant change the UI in doing Background ..
Therefore , i placed the function call in post Execute method of Asynctask class . It doesnot give an error but after the progress bar has reached 100% , then the screen goes black and takes some time to start the new activity.
How can i display the progress bar and make the function call simultaneously.??plz help , m in distress
here is the code
package com.integrated.mpr;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Progess extends Activity implements OnClickListener{
static String[] display = new String[Choose.n];
Button bprogress;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.progress);
bprogress = (Button) findViewById(R.id.bProgress);
bprogress.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bProgress:
String x ="abc";
new loadSomeStuff().execute(x);
break;
}
}
public class loadSomeStuff extends AsyncTask<String , Integer , String>{
ProgressDialog dialog;
protected void onPreExecute(){
dialog = new ProgressDialog(Progess.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
for(int i = 0 ;i<40;i++){
publishProgress(5);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
dialog.dismiss();
String y ="abc";
return y;
}
protected void onProgressUpdate(Integer...progress){
dialog.incrementProgressBy(progress[0]);
}
protected void onPostExecute(String result){
display = new Logic().finaldata();
Intent openList = new Intent("com.integrated.mpr.SENSITIVELIST");
startActivity(openList);
}
}
}
You can't dismiss the dialog in doInBackground() - even dismissing a dialog needs the UI task. Move dialog.dismiss() to onPostExecute() of the AsyncTask.

confusion to pass argument in asyncTask

In my application i get image from server and those image build animation.this all things are gone be right way and i create method for it.this is the method::
package com.animation;
import java.io.InputStream;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
public class animation extends Activity {
Button Buttona;
AnimationDrawable animation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView img = (ImageView) findViewById(R.id.simple_anim);
animation = new AnimationDrawable();
try {
for(int i=0;i<54;i++)
{
xyz("girl000",i);
}
animation.setOneShot(false);
} catch (Exception e) {
}
img.setBackgroundDrawable(animation);
img.post(new Starter());
}
public void xyz(String str,int x)
{
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
"http://201.109.115.111/MRESC/images/test/girl/"+"girl000"+x+".png")
.getContent());
Drawable frame =new BitmapDrawable(bitmap);
animation.addFrame(frame, 50);
} catch (Exception e) {
}
}
class Starter implements Runnable {
public void run() {
animation.start();
}
}
}
now my problem is it is take much time to load image from server so simply i plan to use asyncTask. but problem is i cant get judgment that how can i do this?
can you give me example(Note : i know asyncTask and use already but problem is passing argument as per my xyz() method declare)
Thanks
nik
Here is the code:
Note that the loop now is in the background thread
After each loop, you publish the progress to setup the animation frame
At the very end, you run onPostExecute to run the remaining code
Note, that this is just a skeleton and rough sketches, you need to understand and debug it if there is any problem. I haven't run the code yet
public class Animation extends Activity {
Button Buttona;
AnimationDrawable animation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
animation = new AnimationDrawable();
AsyncTask asyncTask =
new AsyncTask() {
#Override
protected Void doInBackground(Void... params) {
try {
// Execute this whole loop in background, so it doesn't
// block your UI Thread
for(int i=0;i<54;i++) {
xyz("girl000",i);
}
} catch (Exception e) {
return null;
}
}
public void xyz(String str,int x) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
"http://201.109.115.111/MRESC/images/test/girl/"+"girl000"+x+".png")
.getContent());
// publish progress so that the bitmap is set on the UI Thread
publishProgress(bitmap);
} catch (Exception e) {
// handle error
}
}
#Override
protected void onProgressUpdate(Bitmap... result) {
// handle the progress update to add the animation frame
Bitmap bitmap = result[0];
Drawable frame =new BitmapDrawable(bitmap);
animation.addFrame(frame, 50);
}
#Override
protected void onPostExecute(Void result) {
if(result != null) {
// execute the rest of your instruction after the loop is over here
animation.setOneShot(false);
ImageView img = (ImageView) findViewById(R.id.simple_anim);
img.setBackgroundDrawable(animation);
img.post(new Starter());
} else {
// handle error
}
}
};
asyncTask.execute();
}
class Starter implements Runnable {
public void run() {
animation.start();
}
}
}

Categories

Resources