ProgressDialog freezes in async task - android

I am reading lat/lon from file, creating polygon and adding it to the map in AsyncTask. Everything is working fine - except progressDialog allways freezes at start of the action and dismissed after action is completed.This is my code:
UPDATED CODE:
private class shpLoading extends AsyncTask<GoogleMap, List<LatLng>, String> {
private ProgressDialog dialog;
private String path;
private int loaded;
public void setPath(String p){
this.path = p;
}
#Override
protected String doInBackground(GoogleMap... params) {
final ShpReader shpRead = new ShpReader();
try {
shpRead.read(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidShapeFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.setMax(shpRead.daugiakampiai().size());
int i = 0;
for(List<LatLng> a: shpRead.polygons()){
function.arAntLinijos(a);
for(int h = 0; h < a.size()-1; h++){
LatLng point = function.midPoint(a.get(h), a.get(h+1));
a.add(h+1, point);
h++;
if(i > 3000){
message("You reached max count!");
break;
}
}
publishProgress(a);
i++;
}
return "Done";
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(Measuring.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage(getString(R.string.loading));
dialog.setCancelable(false);
dialog.setProgress(0);
dialog.show();
}
}
#Override
protected void onProgressUpdate(List<LatLng>... values) {
dialog.setProgress(loaded++);
Polygon daug = mMap.addPolygon(new PolygonOptions()
.addAll(values[0])
.strokeWidth(1)
.strokeColor(Color.RED)
.fillColor(0x3F00FF00));
plotai.add(new Polygons(db.getMaxFieldID()+1, daug));
daug = null;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
}

Because you should draw your polygons not in onProgressUpdate method, but in doInBackground method. In onProgressUpdate method you have to update progress in your ProgressDialog object (in your code ProgressDialog is showed, but not updated its progress at all).

Related

Progress Bar with AsyncTask in Android

I have a function name CreateVideo(), the problems are:
Because function must be run until it finishs to create a video, I cannot know how many percent completed of the video.
Did I put the function at a right place?
Here is the code:
private class MyVideo extends AsyncTask<Void, Void, String> {
private Context context;
private String output;
private String quality;
private FramePackage framePackage;
CreateMP4Video createMP4Video;
public MyVideo(Context context, FramePackage framePackage, String output, String quality) {
// TODO Auto-generated constructor stub
this.context = context;
this.output = output;
this.quality = quality;
this.framePackage = framePackage;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create Video Maker
createMP4Video = new CreateMP4Video(context, framePackage, output, quality);
// Create progress
mProgress = new ProgressDialog(MainActivity.this);
mProgress.setTitle("Please Wait..");
mProgress.setMessage("Creating Video...");
mProgress.setProgressStyle(mProgress.STYLE_HORIZONTAL);
mProgress.setProgress(0);
// set Max = total number of frame
mProgress.setMax(framePackage.getCount());
mProgress.setCancelable(false);
mProgress.show();
};
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
createMP4Video.CreateVideo();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (mProgress.getProgress() <= mProgress.getMax()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateBarHandler.post(new Runnable() {
public void run() {
// get the current frame (frame 1, 2, 3,...)
// that already added to video
// In thist case, it always get the last frame
// progress bar run from 0% to 100% directly
mProgress.setProgress(createMP4Video.getCurrentFrame());
}
});
if (mProgress.getProgress() == mProgress.getMax()) {
mProgress.dismiss();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
}
}
Thank you in advance!
Put theprogress dialog in onPreExecute() method as u have done
// Create progress
mProgress = new ProgressDialog(MainActivity.this);
mProgress.setTitle("Please Wait..");
mProgress.setMessage("Creating Video...");
mProgress.setProgressStyle(mProgress.STYLE_HORIZONTAL);
mProgress.setProgress(0);
// set Max = total number of frame
mProgress.setMax(framePackage.getCount());
mProgress.setCancelable(false);
mProgress.show();
Dismiss the dialog in onPostExecute
You can take a look at the progressupdate example ONPROGRESS UPDATE

Progressbar with percentage in Asynctask Android

I am writing a code in which I need to move all file and folders to the sdcard. I used Async task for this purpose. During this activity I am showing a progressbar with percentage on my screen instead of just showing me the "Loading..." popup. But it does not meet my requirement.
public class syncMgr extends AsyncTask<String, Long, String> {
public LoginActivity activity;
public Context context;
syncMgr(LoginActivity activity1,Context c)
{
activity = activity1;
context=c;
}
//public ProgressDialog progress;
protected void onPreExecute() {
super.onPreExecute();
activity.progress = ProgressDialog.show(context,"","Files Downloading, Please Wait...",true);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
copyFilesToSdCard();
return null;
}
private void copyFilesToSdCard() {
copyFileOrDir("");
}
private void copyFileOrDir(String path) {
AssetManager assetManager = activity.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() " + path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path=" + fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images")
&& !path.startsWith("sounds")
&& !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir " + fullPath);
for (int i = 0; i < assets.length; ++i) {
publishProgress((int) ((i / (float) 658) * 100));
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images")
&& !path.startsWith("sounds")
&& !path.startsWith("webkit"))
copyFileOrDir(p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void publishProgress(int i) {
// TODO Auto-generated method stub
activity.progress.setProgress(i);
}
#Override
protected void onProgressUpdate(Long... values) {
activity.progress.setProgress(values[0].intValue());
}
#Override
protected void onPostExecute(String result) {
activity.progress.dismiss();
super.onPostExecute(result);
//return "asdas";
//return result;
}
}
Here is my Activity Class Code...
ProgressDialog progress;
public static final int progress_bar_type = 0;
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
progress = new ProgressDialog(this);
progress.setMessage("Downloading file. Please wait...");
progress.setIndeterminate(false);
progress.setMax(100);
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setCancelable(true);
progress.show();
return progress;
default:
return null;
}
}
Have you tried putting the asyncTask initiation code into a worker thread like this?
// set progressBar .VISIBLE first
// then...
new Thread(new Runnable() {
public void run() {
// webview initiation code
}
}).start();
I turn on progressBar visibility beforehand and not in onPreExecute().
Here is how it solved my own problem & here are the docs.

progress dialog displays after task is finished in asynctask

Hi i want to display progressdialog until a command is executed through telnet.
so i use asynctask for that purpose.
private class AsyncAction extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
catch (Exception e)
{
// TODO: handle exception
}
finally
{
pd.dismiss();
}
// pd.dismiss();
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
And i call asynctask in oncreate() like below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
new AsyncAction().execute();
}catch (Exception e) {
e.printStackTrace();
}
}
The problem is that i could not see progressdialog until command executes.
please help me solve the issue.
Thanks in advance.
EDIT
The code to send and read command
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length()-1);
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (ch == lastChar)
{
if (sb.toString().endsWith(pattern))
{
if (sb.toString().contains("cdkk"))
{
disconnect();
break;
}
else
{
return sb.toString();
}
}
else
{
disconnect();
break;
}
}
else if(sb.toString().contains("Failed"))
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String error="Invalid username or password!";
alertbox.setMessage(error);
alertbox.setTitle("Error");
alertbox.show();
System.out.println("bad user name");
disconnect();
break;
}
ch = (char) in.read();
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
}
catch (Exception e) {
e.printStackTrace();
}
}
public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt + " ");
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
Currently you are trying to do Network operations from onPostExecute because this method called from UI Thread . change your code as to get work in proper way
private class AsyncAction extends AsyncTask<String, Void, String>
{
public static boolean status=false;
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
// make status true or false if command successfully executed
status=true;
}
catch (Exception e)
{
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(String result)
{
pd.dismiss();
// check status if true then show AlertDialog
if(status==true){
AlertDialog.Builder alertbox =
new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
else{
// your code here
}
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
You need to show the progress bar in onPreExecute() do the work in doInBackground() and then hide the progress bar in onPostExecute(). onPreExecute() and onPostExecute() are both executed on the main thread, where as doInBackground is executed in the background.
You are doing your work on onPostExecute() method which should be inside doInBackground()
show your progress dialog inside onPreExecute() and dismiss inside onPostExecute().

ConcurrentModificationException in achartengine android

I am developing an android application where I receive eeg signal from bluetooth and display it in real time using achartengine. I use an async task to display the chart and update it. But, I get ConcurrentModificationException everytime. The graph is displayed for sometime and then it gives that error. Below is my code.
mstart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
// tv.setText("Fetal Heart rate loading..");
// index = 0;
flag = true;
if(fhr_alg!=null)
fhr_alg = null;
fhr_alg = new AddStringTask();
algo_done = false;
/*curr = 5;
counter = 0;*/
//// a1.setFlag(true);
//a1.setMax(0);
Thread tt = new Thread()
{
public void run()
{
try{
sleep(600);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
fhr_alg.execute();
}
}
};tt.start();
if (view_eeg1== null) {
LinearLayout layout_eeg1 = (LinearLayout) findViewById(R.id.layout2);
view_eeg1= ChartFactory.getLineChartView(BluetoothConnect.this, eeg1, renderer_eeg1);
// layout_eeg1.
layout_eeg1.addView(view_eeg1);
} else {
view_eeg1.repaint();}
// w1.loadUrl("javascript:callJS()");
mstart.setEnabled(false);
}
});
class AddStringTask extends android.os.AsyncTask<Void, Integer, Integer> {
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
algo_done=true;
//Toast.makeText(Html.this, "Done Algo !", Toast.LENGTH_SHORT).show();
}
#SuppressLint("UseValueOf")
#Override
protected Integer doInBackground(Void... unused) {
try {
for(int r=0;r<=5000;r++){
//Thread.sleep(300);
series1.add(r,data[r]);
// w2.loadUrl("javascript:count(\""+data[r]+"\")");
if(r<=250){
renderer_eeg1.setXAxisMax(250);
}
else if(r>250){
double maxX = series1.getMaxX();
double minX = maxX - 250;
renderer_eeg1.setXAxisMin(minX);
renderer_eeg1.setXAxisMax(maxX);
}
view_eeg1.repaint();
publishProgress((int)data[r]);
SystemClock.sleep(600);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (0);
}
#Override
protected void onProgressUpdate(Integer ... value) {
int fhr=value[0];
view_eeg1.repaint();
w2.loadUrl("javascript:count(\""+fhr+"\")");
//a1.setfhr(curr, fhr);
//curr++;
}
}
can anyone tell me why am I getting this error and how to solve it.
Thanks
problem updating the UI into a Thread that is not an UI Thread so u
have to use a doinbackground as below and remove the code that
modifies the UI in doInbackground

progress dialog circle only showing after task

i've an progress circle that is set inside an AsyncTask. It shows for about a second as the asynctask is executing, then disappears. once the task is completed if i press the back button the circle shows for a long time. why is this?
private class AsyncGetRota extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog= ProgressDialog.show(NfcscannerActivity.this,
"Connecting to Server"," retrieving rota...", true);
//do initialization of required objects objects here
};
#Override
protected Void doInBackground(String... params) {
try {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
cancel(true);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressDialog.dismiss();
};
}
[update]
getRota.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "onclicked getRota");
String[] params = new String[]{"36", "18-09-2012"};
AsyncGetRota agr = new AsyncGetRota();
agr.execute(params);
for(int i = 0; i < 60; i++){
if(agr.isCancelled() == true){
Log.e(TAG, "asyncTask is finished");
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}//end of for loop
Intent intent = new Intent(NfcscannerActivity.this,
GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", rotaArray);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}// end of onclick
});
...
new MyAsyncTask().execute(string);
...
}
class MyAsyncTask extends AsyncTask<String, Void, Whatever > {
...
#Override
protected Whatever doInBackground(String... params) {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
return rotaArray;
}
#Override
protected void onPostExecute(Whatever result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
Intent intent = new Intent(NfcscannerActivity.this, GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", result);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}
}
You should let the execution continue after you start the AsyncTask, and not block it using some loop or something..
try to implement it like this:
protected void onPreExecute() {
dialog = new ProgressDialog(activity);
dialog.setMessage("Processing...");
dialog.show();
}
protected void onPostExecute(Void result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
};
that's always works for me
Couple of problems here, you do not initialize ProgressDialog, initialize a constructor that initializes you ProgressDialog like this...
public AsyncGetRota(Activity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
Then in onPostExecute check if your ProgressDialog is null, like this
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
}

Categories

Resources