Delay in taking screenshots - android

I have an activity in my app where it takes several screen captures and move to next activity on a button click. I want to show some progress or status to the user while taking screenshot(It takes 5-8 seconds). I tries using AsyncTask with runOnUithread(). But no luck. Even when I wrote the whole code in doInBackground(), I don't know why ProgressDialog starts after taking all the screenshots. What is the better way to do this? Here is my code:
public class TakeScreenShots extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(MyActivity.this, "MyTitle",
"Loading .....", true);
}
#Override
protected Void doInBackground(Void... params) {
MyActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
takeScreenshots();
}
});
return null;
}
#Override
protected void onPostExecute(Void unused) {
gotoNextActivity();
this.dialog.dismiss();
}
}

No you are doing wrong, instead capturing in runOnUiThread Directly capture it in doInBackground()
Here is the working example
public class backImageProcess extends AsyncTask<Void, Void, Void>
{
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(MyActivity.this, "MyTitle",
"Loading .....", true);
try {
File mFile= new File(mTempImagename);
if(mFile!=null)
mFile.delete();
} catch (Exception e) {
}
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
mLayoutRoot.setDrawingCacheEnabled(true);
mLayoutRoot.buildDrawingCache();
Bitmap mBitmap= mLayoutRoot.getDrawingCache();
try {
if(mBitmap!=null)
{
FileOutputStream out = new FileOutputStream(mTempImagename);
mBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
}
} catch (Exception e) { }
return null;
}
#Override
protected void onPostExecute(Void result) {
if(this.dialog!=null)
this.dialog.dismiss();
gotoNextActivity();
}
}

I got the answer from an answer in this question. I was setting a drawable to the image view. So, I kept that line on Ui Thread and remaining in doInBackground().

Related

Show progressDialog in Android

I want to show a progressDialog on my page when the user clicks on the button.On click of button i am sorting my results that is a List.Now how can we show a progressDialog on click of a button.Please suggest me
This function i am using to sort that data :
public void sortByDate(View v) {
Collections.sort(tripParseData.getDetails());
setData(tripParseData);
}
After #Monica Suggestion
public void sortByDate(View v) {
new LoadData().execute();
}
class LoadData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
Collections.sort(tripParseData.getCoroprateBookingDetails());
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
setApprovalDetailsData(tripParseData);
}
}
you have to call progressdiolog.show before the long calculation starts and then the calculation has to run in a separate thread. A soon as this thread is finished, you have to call pd.dismiss() to close the prgoress dialog.
here you can see an example:
the progressdialog is created and displayed and a thread is called to run a heavy calculation:
Override
public void onClick(View v) {
pd = ProgressDialog.show(lexs, "Search", "Searching...", true, false);
Search search = new Search( ... );
SearchThread searchThread = new SearchThread(search);
searchThread.start();
}
and here the thread:
private class SearchThread extends Thread {
private Search search;
public SearchThread(Search search) {
this.search = search;
}
#Override
public void run() {
search.search();
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
displaySearchResults(search);
pd.dismiss();
}
};
}
Don't forget to vote me up :)
Paste This Class in ur activity and call new LoadData().execute to start the prgress dialog :
class LoadData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pg=new ProgressDialog(ChartsActivity.this);
pg=pg.show(ChartsActivity.this, "Loding", "Plz Wait...");
}
#Override
protected Void doInBackground(Void... params) {
sortByDate();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pg.dismiss();
}
}
I have not tested it but I think it can help you.
Declare these two objects in your class and member variables.
Thread thread = null;
ProgressDialog bar = null;
Use this logic on your button click listener it can work in your case. I have not tested it but It will give you Idea how things should work. you can also use handlemessage in place of runonuithread
if (thread == null
|| (thread != null && !thread.isAlive())) {
thread = new Thread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//DISPLAY YOUR PROGRESS BAR HERE.
bar = ProgressDialog.show(getApplicationContext(), "LOADING..", "PLEASE WAIT..");
}
});
// SORT COLLECTION HERE
runOnUiThread(new Runnable() {
#Override
public void run() {
//CLOSE YOUR PROGRESS BAR HERE.
bar.dismiss();
}
});
}
});
thread.start();
}
Hope this will help you.
try to use AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
Sample code:
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
//Show UI
//Start your progress bar
showProgress();
}
#Override
protected Void doInBackground(Void... arg0) {
// do your sorting process
return null;
}
#Override
protected void onPostExecute(Void result) {
//Show UI
//dismiss your progress bar
hideProgress();
}
};
task.execute((Void[])null);
Show and hide progress code
public void showProgress() {
progressDialog = ProgressDialog.show(this, "",
"Loading. Please wait...");
progressDialog.setCancelable(false);
}
public void hideProgress() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}

Displaying a ProgressDialog while waiting for a joined Thread

In my Activity, I load the content for a list from a DB, and want to display a ProgressDialog while it´s loading.
I got both working on it´s own, but if I load the data in a thread (which I should do?), the list is displayed before it´s data is loaded. But if I use join, the ProgressDialog doesnt even appear.
How can I combine this? Or is this not possible at all with threads? (AsyncTask maybe?)
Here´s the code for reference:
final ProgressDialog progressD=ProgressDialog.show(ShopSwitchActivity.this, "", "Loading..", true);
Thread myThread = new Thread(new Runnable() {
#Override
public void run() {
try
{
getData();
}catch(Exception e){}
}
});
myThread.start();
try {
myThread.join();
} catch (InterruptedException e) {
}
progressD.dismiss();
EDIT: Updated Code with AsyncTask:
public class LoadList extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
ShopSwitchActivity activity;
public LoadList(ShopSwitchActivity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
protected Boolean doInBackground(final String... args) {
try{
activity.getData();
} catch (Exception e) {
Log.e("error", e.getMessage());
}
return true;
}
}
Edit: My Solution
Using AsyncTask now to load the Data, and after it´s done, I refresh the list with the new data.
You can do it with AsyncTask. Write AsyncTask class in your main class that you want to do your operations. You can create the progress dialog in preexcecute of your async class and dismiss in onpostexecute of async class. Here is how you will do this:
class MyAsync extends AsyncTask<String, Void, Void> {
ProgressDialog pd;
Context co;
MyActivity ma;
public MyAsync (MyActivity ma){
this.ma= ma;
this.co = ma;
pd= new ProgressDialog(co);
}
#Override
protected void onPreExecute() {
this.pd.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
// do your database operations here
return null;
}
#Override
protected void onPostExecute(Void result) {
// show db results and dismiss progress dialog pd.dismiss();
super.onPostExecute(result);
}
}
in MyActivity call as :
MyActivity ma = this;
new MyAsync(ma).execute();
You seem to miss the point of a thread. A thread occurs at the same time as your application. So your app doesn't call start then wait for the thread to be over- if it did you could just use a function. Instead your code continues to run. So if you just call join immediately, you're not doing anything. You'd get around a NetworkOnMainThreadException this way, but you'd still hold up the UI thread making your app totally non-responsive (and as a result not showing the dialog), and you'd eventually crash when a watchdog timer kills you.
Instead, the best way to handle this is to use an AsyncTask. Call getData in doInBackground(). Then dismiss the dialog in onPostExecute.
You should use AsyncTask instead actually.
Here is the link to the library. It is fairly simple:
1) onPreExecute() = show ProgressDialog
2) doInBackground() = execute your code
3) onPostExecute() = dismiss ProgressDialog
Here's a nice tutorial too.
In general:
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(this.context);
dialog.setMessage("Loading...");
dialog.setCanceledOnTouchOutside(false);
}
#Override
protected void onPostExecute(String result) {
if(dialog.isShowing()) {
dialog.dismiss();
}
}
private Thread myThread;
private ProgressDialog mProgDialog;
mProgDialog = ProgressDialog.show(ShopSwitchActivity.this,"","Laden..", true);
myThread= new Thread(new Runnable()
{
public void run()
{
myThread.setPriority(Thread.MIN_PRIORITY);
try
{
getData();
}catch(Exception e){}
runOnUiThread(new Runnable()
{
public void run()
{
if (mProgDialog != null&& mProgDialog.isShowing())
mProgDialog.dismiss();
} }
});
}
});
myThread.start();

Android - Progress Dialog crashes when changing message

I'm new to Android and I'm practicing creating a progress dialog. I want to change the message in the dialog every couple of seconds, but my application crashes when I change the message. Any ideas what I may be doing wrong?
private void progressDialogTest(final ArrayList<String> messages)
{
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>()
{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Progress Dialog");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
for(int i=0; i<messages.size(); i++)
{
/******** APPLICATION SEEMS TO CRASH AT LINE BELOW ********/
progressDialog.setMessage(messages.get(i));
Thread.sleep(3000);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
};
task.execute((Void[])null);
}
Move the code to onProgressUpdate instead, eg:
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
progressDialog.setMessage(messages.get(progress[0]));
}
#Override
protected void doInBackground(Void... arg0) {
/* ... */
//progressDialog.setMessage(messages.get(i)); Change this line to
publishProgress(i);
/* ... */
}

My ProgressDialog doesn't dismiss even after the view has been loaded.

I want to show a Progress-Dialog before my view has been loaded.
First i wrote the code in onCreate() but the dialog doesn't appear in that case. So i wrote it in onResume() but in this case, it doesn't disappear even after the view has been loaded. can anyone tell whats going wrong here?
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
dialog = ProgressDialog.show(this, "", "Please wait...", true);
//dialog.cancel();
new Thread()
{
public void run()
{
try
{
sleep(1500);
// do the background process or any work that takes time to see progress dialog
}
catch (Exception e)
{
Log.e("tag",e.getMessage());
}
// dismiss the progressdialog
dialog.dismiss();
}
}.start();
citySelected.setText(fetchCity);
spinner.setSelection(getBG);
}
You cant update UI(which is in main UIthread) from other threads. If you want to run any query in the background, you can use AsyncTask.
In onPreExecute method, show dialog and onPostExecute you can dismiss the dialog.
If you want to use Thread, then update UI using handlers.
Using AsyncTask
public class MyAsyncTask extends AsyncTask<String, Void, String> {
ProgressDialog dialog = new ProgressDialog(ActivityName.this);
#Override
protected void onPreExecute() {
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
super.onPostExecute(result);
}
}
In Activity onCreate Method,
MyAsyncTask task = new MyAsyncTask();
task.execute();
better to use Asynctask ......... but if you still want same or want to know the solution only then can try
new Thread()
{
public void run()
{
try
{
sleep(1500);
// do the background process or any work that takes time to see progress dialog
}
catch (Exception e)
{
Log.e("tag",e.getMessage());
}
YourActivity.this.runOnUIThread(new Runnable(){
#Override
public void run(){
// dismiss the progressdialog
dialog.dismiss();
});
}
}.start();
You can use AsyncTask. It is better than Thread
private class DownloadingProgressTask extends
AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
downloadFile(b.getString("URL"));
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}

Dismiss a dialog when a thread is done

I'm creating a thread in android for a time consuming operation. I want the main screen to show a progress dialog with a message informing that the operation is in progress, but I want that dialog to dismiss once the thread is done. I've tried with join but it locks the thread and doesn't show the dialog. I tried using:
dialog.show();
mythread.start();
dialog.dismiss();
but then the dialog doesn't show. How can I make that sequence but wait for the thread to end without locking the main thread?
This is as far as I got:
public class syncDataElcanPos extends AsyncTask<String, Integer, Void> {
ProgressDialog pDialog;
Context cont;
public syncDataElcanPos(Context ctx) {
cont=ctx;
}
protected void onPreExecute() {
pDialog = ProgressDialog.show(cont,cont.getString(R.string.sync), cont.getString(R.string.sync_complete), true);
}
protected Void doInBackground(String... parts) {
// blablabla...
return null;
}
protected void onProgressUpdate(Integer... item) {
pDialog.setProgress(item[0]); // just for possible bar in a future.
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
But when I try to execute it, it gives me an exception: "Unable to add window".
When your thread is done, use the runOnUIThread method to dismiss the dialog.
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
To do that there is two ways to do it , ( and i prefer the first second one : AsyncTask ) :
First : you display your alertDialog , and then on the method run() you should do like this
#override
public void run(){
//the code of your method run
//....
.
.
.
//at the end of your method run() , dismiss the dialog
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
Second : Using an AsyncTask like this :
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
//create and display your alert here
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Downloading data ...", true);
}
protected Void doInBackground(Void... unused) {
// here is the thread's work ( what is on your method run()
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
//dismiss the alert here where the thread has finished his work
pDialog.dismiss();
}
}
well in AsyncTask in the on postexecute you can call dismiss
here is an example from other thread
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Retrieving data ...", true);
}
protected Void doInBackground(Void... unused) {
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}

Categories

Resources