I am trying to show a progress dialog with percentage while executing a long running code, I used AsyncTask for this purpose but it did not work, the functionality is as follow: I get the array paths of all gallery images and then I process these images and extract the descriptor vector of each image and convert it to JSON string and then store these strings into sqlite, but my code takes lot of time( few minutes ), so what I need is to show a progress dialog with percentage in order to know the start and end of the task, this task I need to start it when I press a button. Below is my code:
public void FillDataBase(){
ArrayList<String> paths = getFilePaths();
for (int i = 0; i < paths.size(); i++) {
Mat mat = new Mat();
BitmapFactory.Options bmOptions1 = new BitmapFactory.Options();
//bmOptions1.inSampleSize=4;
Bitmap bitmap0 = BitmapFactory.decodeFile(paths.get(i).toString(), bmOptions1);
Bitmap bitmap = getRotated(bitmap0, paths.get(i).toString());
//Utils.bitmapToMat(bitmap, mat);
Mat matRGB = new Mat();
Utils.bitmapToMat(bitmap, matRGB);
Imgproc.cvtColor(matRGB, mat, Imgproc.COLOR_RGB2GRAY);
org.opencv.core.Size s2 = new Size(3, 3);
Imgproc.GaussianBlur(mat, mat, s2, 2);
FeatureDetector detector2 = FeatureDetector.create(FeatureDetector.ORB);
MatOfKeyPoint keypoints2 = new MatOfKeyPoint();
detector2.detect(mat, keypoints2);
DescriptorExtractor extractor2 = DescriptorExtractor.create(DescriptorExtractor.ORB);
Mat descriptors2 = new Mat();
extractor2.compute(mat, keypoints2, descriptors2);
// String matimage = matToJson(mat);
String matkeys= keypointsToJson(keypoints2);
String desc = matToJson(descriptors2);
mat m = new mat(desc, matkeys);
DataBaseHandler db = new DataBaseHandler(getApplicationContext());
db.addmat(m);
}
Asynctask Code (I call the FillDatabase() in public void run of the thread):
private class ProgressTask extends AsyncTask<Void,Void,Void>{
private int progressStatus=0;
private Handler handler = new Handler();
// Initialize a new instance of progress dialog
private ProgressDialog pd = new ProgressDialog(RGBtoGrey.this);
#Override
protected void onPreExecute(){
super.onPreExecute();
pd.setIndeterminate(false);
// Set progress style horizontal
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// Set the progress dialog background color
pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.YELLOW));
// Make the progress dialog cancellable
pd.setCancelable(true);
// Set the maximum value of progress
pd.setMax(100);
// Finally, show the progress dialog
pd.show();
}
#Override
protected Void doInBackground(Void...args){
// Set the progress status zero on each button click
progressStatus = 0;
// Start the lengthy operation in a background thread
new Thread(new Runnable() {
#Override
public void run() {
FillDataBase();
while(progressStatus < 100){
// Update the progress status
progressStatus +=1;
// Try to sleep the thread for 20 milliseconds
try{
Thread.sleep(20);
}catch(InterruptedException e){
e.printStackTrace();
}
// Update the progress bar
handler.post(new Runnable() {
#Override
public void run() {
// Update the progress status
pd.setProgress(progressStatus);
// If task execution completed
if(progressStatus == 100){
// Dismiss/hide the progress dialog
pd.dismiss();
}
}
});
}
}
}).start(); // Start the operation
return null;
}
protected void onPostExecute(){
// do something after async task completed.
}
And finally i call the Asynctask like this:
testButton0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ProgressTask().execute();
}
});
You could do something like this:
private static class InsertAllPersonsToFirebaseTask extends AsyncTask<Void, Float, Void> {
private List<Person> personList;
private ElasticDownloadView mElasticDownloadView;
private DatabaseReference mDatabase, pushedKey;
private Person person;
public InsertAllPersonsToFirebaseTask(List<Person> personList, ElasticDownloadView mElasticDownloadView) {
this.personList = personList;
this.mElasticDownloadView = mElasticDownloadView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (mElasticDownloadView != null) {
this.mElasticDownloadView.setVisibility(View.VISIBLE);
this.mElasticDownloadView.startIntro();
}
}
#Override
protected Void doInBackground(Void... voids) {
mDatabase = FirebaseDatabase.getInstance().getReference();
for (int i = 0; i < personList.size(); i++){
pushedKey = mDatabase.child("Persons").push();
person = new Person();
person.setPersonId(System.currentTimeMillis());
person.setName(personList.get(i).getName());
pushedKey.setValue(person);
//This line is for update the onProgressUpdate() method
publishProgress(((i+1)/(float)personList.size()* 100));
if (isCancelled()){
break;
}
}
return null;
}
#Override
protected void onProgressUpdate(Float... progress) {
if (mElasticDownloadView != null){
mElasticDownloadView.setProgress(progress[0]);
}
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (mElasticDownloadView != null){
mElasticDownloadView.setVisibility(View.GONE);
}
}
}
You can use any type of progressbar. I have used ElasticDownloadview progressbar.
Then:
testButton0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new InsertAllPersonsToFirebaseTask(personArrayList,mElasticDownloadView).execute();
}
});
Related
I am developing an android app where I need to show a ProgressBar until the loop execution is finished. After execution it will go to the nextActivity.
here is my java code
public class Image_Recognition extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image__recognition);
Button btnNextPage = (Button) findViewById(R.id.btnNextPage);
btnNextPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> items = textRecognizer.detect(frame);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < items.size(); ++i) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
stringBuilder.append('.');
txtResult.setText(stringBuilder.toString());
str = stringBuilder.toString();
Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
myintent.putExtra("translate", str);
startActivity(myintent);
}
});
}
//}
}
You can try with this.
final ProgressDialog dialog = new ProgressDialog(Image_Recognition.this);
btnNextPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.show(Image_Recognition.this, "", "Please wait...", true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational())
Log.e("ERROR", "Detector dependencies are not yet available");
else {
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> items = textRecognizer.detect(frame);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < items.size(); ++i) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
stringBuilder.append('.');
txtResult.setText(stringBuilder.toString());
str = stringBuilder.toString();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.dismiss();
dialog.setCancelable(true);
Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
myintent.putExtra("translate", str);
startActivity(myintent);
}
});
}
},5000);
You have two problems here.
ProgressBar, which you can use ProgressDialog or a ProgressBar in your XML and show it, while hiding the rest of your IU.
Blocking the UI
You are running your loop directly from you click listener, which means that you will block your UI and even if you show some sort of progress, it will be blocked till your loop is over, you need to start a thread and run your loop in.
Here's a not very clean version of you click listener impl
final ProgressDialog dialog = new ProgressDialog(Image_Recognition.this);
dialog.show();
new Thread(new Runnable() {
#Override
public void run() {
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> items = textRecognizer.detect(frame);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < items.size(); ++i) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
stringBuilder.append('.');
txtResult.setText(stringBuilder.toString());
str = stringBuilder.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.dismiss();
Intent myintent = new Intent(Image_Recognition.this, ReminderAddActivity.class);
myintent.putExtra("translate", str);
startActivity(myintent);
}
});
}
}).start();
You could use Async Task and run your loop in doInBackground()
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
public MyTask(ProgressDialog pd){
this.pd=pd;
}
#Override
protected void onPreExecute () {
super.onPreExecute();
pd.setMessage("Uploading . . .");
pd.show();
pd.setCancelable(false);
}
#Override
protected Void doInBackground (Void...voids){
for(int i=0;i<10000000;i++){
System.out.print(i);
}
return null;//download file
}
#Override
protected void onPostExecute (Void aVoid){
super.onPostExecute(aVoid);
pd.dismiss();
}
}
and in activity call new MyTask(pd).execute();
I have an Android App and I want to download a big file.
REST API implementation is made with AndroidAnnotations. I need to show a progressbar with the download of a big file using this REST Client (made by AndroidAnnotations).
How I to do that?
Regards
Hello Its to late for answering this question but this will be helpful who are still finding ans with Android-annotation
You can check your image progress by little bit manipulation of code and here is what i have created my
Custom converter Class:-
public class CustomConverter extends FormHttpMessageConverter {
OnProgressListener mOnProgressListener;
public CustomConverter() {
super();
List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>();
partConverters.add(new ByteArrayHttpMessageConverter());
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setWriteAcceptCharset(false);
partConverters.add(stringHttpMessageConverter);
partConverters.add(new ProgressResourceHttpMessageConverter());
setPartConverters(partConverters);
}
// public ProgressFormHttpMessageConverter setOnProgressListener(OnProgressListener listener) {
// mOnProgressListener = listener;
// return this;
// }
class ProgressResourceHttpMessageConverter extends ResourceHttpMessageConverter {
#Override
protected void writeInternal(Resource resource, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
InputStream inputStream = resource.getInputStream();
OutputStream outputStream = outputMessage.getBody();
byte[] buffer = new byte[2048];
long contentLength = resource.contentLength();
int byteCount = 0;
int bytesRead = -1;
Log.d("<3 <3 <3", "called");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
byteCount += bytesRead;
Log.d("<3 <3 <3 ** ", "progress" + String.valueOf((byteCount * 100) / contentLength));
if(mOnProgressListener != null) {
mOnProgressListener.onProgress(resource, byteCount, (int) contentLength);
}
}
outputStream.flush();
}
}
public interface OnProgressListener {
void onProgress(Resource resource, int downloaded, int downloadSize);
}
}
--> you can check your progress with log :)
Code Usage
-> Your rest class will be as follow:-
#Rest(rootUrl = CommonUtils.BASE_URL, converters = {ByteArrayHttpMessageConverter.class,
CustomConverter.class, StringHttpMessageConverter.class})
public interface CustomRest extends RestClientErrorHandling {
#Post(pUrlSignUp)
String _SignUp(MultiValueMap<String, Object> multiValueMap);
}
Of course, you will have to use AsyncTask for downloading purpose:
You can use its methods onPreExecute and onPostExecute for showing and dismissing the ProgressDialog respectively.
Example:
public class DownloadTask extends AsyncTask<String, Integer, String>
{
ProgressDialog pDialog;
Activity activity; //pass your activity reference while initialize this.
public DownloadTask (Activity activity){
this.activity = activity;
}
#Override
protected void onPreExecute()
{
pDialog = new ProgressDialog(activity);
pDialog.setMessage("Downloading file...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args)
{
//download file's code here
}
#Override
protected void onPostExecute(String result)
{
pDialog.dismiss();
}
}
Hope this helps.
> use AsyncTask method "on progressupdate " to show progress
public class download extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
With AndroidAnnotations, you can use background threads and publishing progress easily:
#EActivity
public class MyActivity extends Activity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle)
doSomeStuffInBackground();
}
#Background
void doSomeStuffInBackground() { // will run on a background thread
publishProgress(0);
// Do some stuff
publishProgress(10);
// Do some stuff
publishProgress(100);
}
#UiThread
void publishProgress(int progress) { // will run on the UI thread
// Update progress views
}
}
Now you can only have to figure out how you can get progress events. This answer can give a great inspiration. Unfortunetaly AFAIK there is no built-in callback for that in Spring Android Rest Template.
I was looking to solve this same problem, its being two months now. Finally found a good example, I cant believe everybody copy paste the same in AndroidAnnotations docs, if that were enough, we wouldnt be here seeking for help.
Here is the link where you can see the example
I made some modifications my self, for the moment its working with some toasts, but I hope to comeback with an actual loading animation to share:
/*This background handles my main thread in UI and the progress publish*/
#Background
void thisGETJSON() {
publishProgress(0);
publishProgress(50);
publishProgress(100);
showJSONInUI();
}
/*Here the progress is published and the main UI thread is also called*/
#UiThread
void publishProgress(int progress) {
if (progress == 0) {
Toast toast = Toast.makeText(getApplicationContext(), "Just a sec please", Toast.LENGTH_SHORT);
toast.show();
} else if (progress == 50) {
Toast toast = Toast.makeText(getApplicationContext(), "Loading", Toast.LENGTH_SHORT);
toast.show();
} else if (progress == 100) {
Toast toast = Toast.makeText(getApplicationContext(), "Thanks for waiting", Toast.LENGTH_SHORT);
toast.show();
}
/*This is the main UI thread here I do cool stuff with the JSON objects*/
#UiThread
Void showJSONInUI(); {
//Here I do something with the objects in the JSON
}
I have a custom method of my class that (on my Android phone) takes 2-3 second to finish, and I would like to surround it with a progress bar.
Here is my method:
public void getQuestionsForSelectedCategory(){
ArrayList<Question> temp = (ArrayList<Question>) this.clone();
ArrayList<Question> tempGroup;
this.clear();
for(int i=0;i<2;i++){
tempGroup = new ArrayList<Question>();
for(int j=0;j<temp.size();j++)
if((temp.get(j).getGroup()==i+1)&&(temp.get(j).getCategory().contains(category)||temp.get(j).getCategory().equals("*")))
tempGroup.add(temp.get(j));
getQuestionsForSelectedGroup(tempGroup, numbersByGroup[i], pointsByGroup[i]);
}
tempGroup = new ArrayList<Question>();
for(int i=0;i<temp.size();i++){
int a = temp.get(i).getGroup();
if((a==3||a==4||a==5||a==6||a==7))
if(temp.get(i).getCategory().contains(category)||temp.get(i).getCategory().equals("*"))
tempGroup.add(temp.get(i));
}
Collections.shuffle(tempGroup);
getQuestionsForSelectedGroup(tempGroup, numbersByGroup[2], pointsByGroup[2]);
if(category.equals("C")){
tempGroup = new ArrayList<Question>();
for(int i=0;i<temp.size();i++)
if(temp.get(i).getCategory().equals(category))
tempGroup.add(temp.get(i));
getQuestionsForSelectedGroup(tempGroup, 10, 30);
}
}
And here is what I try to do:
barProgressDialog = new ProgressDialog(this);
barProgressDialog.setTitle("Preparing Test");
barProgressDialog.setMessage("Preparing Test");
barProgressDialog.setProgressStyle(barProgressDialog.STYLE_HORIZONTAL);
barProgressDialog.setProgress(0);
barProgressDialog.setMax(100);
barProgressDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
getQuestionsForSelectedCategory();
while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {
updateBarHandler.post(new Runnable() {
public void run() {
barProgressDialog.incrementProgressBy(2);
}
});
if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {
barProgressDialog.dismiss();
}
}
} catch (Exception e) {
}
}
}).start();
}
For the current code the progress bar fills up to 100 but it does nothing.
You could use an AsyncTask to achieve this, whilst publishing your progress during the task.
AsyncTask<Void, Integer, Void> task = new AsyncTask<Void, Integer, Void>() {
#Override
protected Void doInBackground(Void... voids) {
getQuestionsForSelectedCategory();
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
barProgressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void aVoid) {
barProgressDialog.dismiss();
}
}
task.execute();
Ensure your getQuestionsForSelectedCategory and getQuestionsForSelectedGroup methods are inside the AsyncTask and within the loops you can call publishProgress(int progress) to update the progress dialog.
I want to show a progress dialog while loading some data from remote server :
I'm using the following thread in order to get the data and it's working, but i'm not able to show the progress bar on the activity:
public class Request {
public String text ;
public boolean downloadText(String urlStr) {
final String url = urlStr;
new Thread () {
public void run() {
int BUFFER_SIZE = 2000;
InputStream in = null;
Message msg = Message.obtain();
msg.what=2;
try {
in = openHttpConnection(url);
InputStreamReader isr = new InputStreamReader(in);
int charRead;
text = "";
char[] inputBuffer = new char[BUFFER_SIZE];
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
text += readString;
inputBuffer = new char[BUFFER_SIZE];
}
Bundle b = new Bundle();
b.putString("text", text);
msg.setData(b);
in.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
would you please tell me how can i do it !!
create the class as below and just call the object of this class.
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog Asycdialog = new ProgressDialog(ActivityName.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
Asycdialog.setMessage("Loading...");
Asycdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// do the task you want to do. This will be executed in background.
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Asycdialog.dismiss();
}
}
Use progressDialog
final ProgressDialog progress=ProgressDialog.show(youractivity.this,"","message");
new Thread()
{
public void run()
{
try{
youractivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
// your code
}
});
}
catch(Exception e)
{
}
progress.dismiss();
}
}.start()
Also, note that if you want to use Toast, you should use runOnUiThread
If you do not want to change the structure of your code, you can use runOnUiThread or an Handler to show and dissmiss the progress dialog. Show it when the firs line of the run method is excuted and dismiss it in the finally block.
public void run() {
runOnUiThread(new Runnable() {
public void run(){
// show progress dialog
}
});
/// your code here
try {
} catch (IOException e) {
} finally {
runOnUiThread(new Runnable() {
public void run(){
// dismiss progress dialog
}
});
}
}
Create Progress Dialog in AsyncTask
private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... args) {
// do background work here
return null;
}
protected void onPostExecute(Void result) {
// do UI work here
}
}
pDialog = ProgressDialog.show(context, null, "Loading...", true);
pDialog.setCancelable(false);
new Thread() {
public void run() {
// handle the exception somehow, or do nothing
// run code on the UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
// do yor ui part here
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}.start();
When user clicks button, will go to Activity B from Activity A.
However, since in Activity B, data will be downloaded from Internet, I would like to add a progress dialog.
Sometimes, the connection will be very fast, less than one second and sometimes will be more than 5 seconds.
If the progress dialog shows <1 sec, I think it is very bad for user experience.
So, I would like to add a minimum loading time, for example, 2 seconds.
That means even the loading time is less than 2 seconds, the progress dialog will also at least show 2 seconds.
Is there any ways to do so?
you can use Below Code. Pass Time and Object of your Dialog here.
public void timerDelayRemoveDialog(long time, final Dialog d){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
d.dismiss();
}
}, time);
}
EDITED
you can Use this Sample Code :
class LoginProgressTask extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
Thread.sleep(4000); // Do your real work here
} catch (InterruptedException e) {
e.printStackTrace();
}
return Boolean.TRUE; // Return your real result here
}
#Override
protected void onPreExecute() {
showDialog(AUTHORIZING_DIALOG);
}
#Override
protected void onPostExecute(Boolean result) {
// result is the value returned from doInBackground
removeDialog(AUTHORIZING_DIALOG);
Intent i = new Intent(HelloAndroid.this, LandingActivity.class);
startActivity(i);
}
}
My solution (worked well):
private class ProgressTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
long timestamp1;
long timestamp2;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(YOUR_CONTEXT);
dialog.setCancelable(false);
dialog.setMessage("Please wait...");
dialog.show();
timestamp1 = System.currentTimeMillis();
}
#Override
protected Void doInBackground(Void... params) {
//doSomething ...
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//doSomething ...
timestamp2 = System.currentTimeMillis();
long timeDifference = timestamp2 - timestamp1;
if (timeDifference >= 2000) {
dialog.dismiss();
} else {
Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
dialog.dismiss();
}
}, 2000 - timeDifference);
}
}
}
Here is another version. Using SystemClock does not require try catch block.
ParentActivity.this is the context where Task is executed.
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.SystemClock;
protected class Task extends AsyncTask< String, Void, String >
{
private ProgressDialog mDialog = new ProgressDialog( ParentActivity.this );
private long mTaskStartTimeMills;
protected void onPreExecute()
{
mTaskStartTimeMills = System.currentTimeMillis();
mDialog.setMessage( "Loading.." );
mDialog.show();
}
protected String doInBackground( String... arg )
{
// TODO
return null;
}
protected void onPostExecute( String json )
{
final long timeToWait = 1000 - ( System.currentTimeMillis() - mTaskStartTimeMills );
if ( timeToWait > 0 )
{
SystemClock.sleep( timeToWait );
}
mDialog.dismiss();
}
}
this may helps you
new AsyncTask<Void, Void, Void>() {
ProgressDialog mDialog;
ArrayList<String> files;
#Override
protected void onPreExecute() {
mDialog = new ProgressDialog(MyMainAct.this);
mDialog.setMessage("Loading");
mDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// do your work here
Log.i("Share Media MyMainAct", " newFiles is called path is - " + path +"/" + spndirectory.getSelectedItem().toString());
files = getFiles(path + "/" + spndirectory.getSelectedItem().toString());
return null;
}
#Override
protected void onPostExecute(Void result){
if (mDialog != null && mDialog.isShowing()){
mDialog.dismiss();
}
setFileAdapter(files);
}
}.execute();