Fix ProgressDialog showing up after download is complete - android

I have a ListView that is populated with articles. When the user long clicks on an article, I want to download its summary and display it to the user. I have a function in AsyncTask (NOT doInBackground...) that takes care of the download. During the downloading process, I want to display a ProgressDialog. Since the download is on the main thread, there is a delay when I long click an article and the ProgressDialog shows AFTER the download is complete. How can I get it to show DURING the download?
I have tried these methods but I don't really understand it since I am a beginner in Android Development. The app freezes while its downloading and shows the Dialog after it's done.
ProgressDialog shows up after thread is done
display progressdialog while listview is loading
HomeActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
trendingList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
try {
...
} catch (Exception e) {
String link = homeLinks.get(position);
//TASK TO DOWNLOAD SUMMARIES FROM ASYNCTASK
task.downloadSummary(link);
adapter.notifyDataSetChanged();
}
return true;
}
});
Background Class
public class BackgroundTask extends AsyncTask<String, Void, String> {
ProgressDialog progress = new ProgressDialog(HomeActivity.this);
//SHOW DIALOG AND THEN DOWNLOAD SUMMARIES
public void downloadSummary(String address){
progress.setMessage("Downloaded summary ");
progress.show();
...

When initializing an AsyncTask you must allocate the 3 dependent methods of this thread, onPreExecute that will allocate your ProgressDialog, the InBackground that put the job you want to perform and the onPostExecute that reotrna the result of your work and you close your progressDialog
It had stayed like this
public class BackgroundTask extends AsyncTask<String, Void, String> {
ProgressDialog progress = new ProgressDialog(HomeActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.setMessage("Downloaded summary ");
progress.show();
}
#Override
protected void doInBackground(String... strings) {
//Ação do Trabalho
}
#Override
protected void onPostExecute(String result) {
progress.dismiss();
Log.e("Work", "Result "+result);
}
}
it is mandatory the google background method does not like when ignoring this use being an AsysnTask will have to use it. If on the contrary if it is a fast job use a thread invoked with run

Related

asyncTask onProgressUpdate does not work at 2nd invoking

im using asyncTask to showing a download progress , my download will be done by a library named "file-downloader" in my main activity.
it's github page is "https://github.com/wlfcolin/file-downloader"
my custom dialog shows when i click to my specified button , and download task and progressBar starts when i press download button in this custom dialog
all thing is ok and progressBar works fine.
but when i dismiss this dialog and another time i invoke this dialog the progressBar does not work !
i save download status in database using the fileDownloader library listeners and anothe time i invoke custom dialog it read from database
and detect downloadProgress is currently running but we see no changing in custom dialog's progressBar , what is the problem ?
activity code
public class MainActivity extends AppCompatActivity {
/*
/
/ some variables
/
*/
public static int downloadedFile2SizePercent = 0 ; // downloaded file percent
public static int downloadingFileStatus = 0; // downloading status
Button myBtn ;
DownloadDialog dd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
myBtn = (Button)findViewById(R.id.button22);
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dd = new DownloadDialog(mContext,1);
dd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dd.show();
}
});
/*
/ downloadingFileStatus value manages here by file downloader listeners correctly and saves as static variable and also in database
/ downloadedFile2SizePercent value manages here by file downloader listeners correctly and saves as static variable
/
*/
}
}
DownloadDialog Class
public class DownloadDialog extends Dialog implements View.OnClickListener{
public Context c;
public Button download, delete;
private ProgressBar pb;
ProgressTask progressTask;
private int downloadStatus;
private String downloadLink;
private int downloadID
public DownloadDialog(Context a, int downloadId) {
super(a);
this.c = a;
this.downloadId = downloadId
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.download_dialog);
download = (Button) findViewById(R.id.downloaddialot_downloadbtn);
delete = (Button) findViewById(R.id.downloaddialot_deletebtn);
download.setOnClickListener(this);
delete.setOnClickListener(this);
pb = (ProgressBar)findViewById(R.id.progressBar);
pb.setMax(100);
pb.setProgress(0);
//database is opend at mainActivity it's static
downloadStatus=Integer.parseInt(MainActivity.prDb.intSearch(downloadId));// detects download status --> 0 is "notDownloadedYet" and
// 1 is "downloading" and 2 is "downloaded"
downloadLink= MainActivity.puDb.intSearch(downloadId);//detects download link
progressTask = new ProgressTask();
if(downloadStatus==1){
pb.setProgress(MainActivity.downloadedFile2SizePercent);//this code line works every 2nd and after dialog invoking
progressTask.execute(true);
Toast.makeText(c,"test task progress for 2nd started", Toast.LENGTH_SHORT).show();//this code line works every 2nd and afterdialog invoking
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.downloaddialot_downloadbtn:
FileDownloader.start(downloadLink); // download task starts here
progressTask.execute(true);
Toast.makeText(c,"download task progress for 1nd started", Toast.LENGTH_SHORT).show();
break;
case R.id.downloaddialot_deletebtn:
if(downloadStatus==2){
// delete codes
}
break;
}
}
public class ProgressTask extends AsyncTask<Boolean, Integer, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Boolean... params) {
while (MainActivity.downloadedFile2SizePercent!=100){
publishProgress(MainActivity.downloadedFile2SizePercent);
}
if(MainActivity.downloadedFile2SizePercent==100){
publishProgress(MainActivity.downloadedFile2SizePercent);
}
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
pb.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
downloadStatus=2; //also saves in database by download listeners in mainActivity
}
}
}
The progress bar just like any other UI element can only be managed or updated from the main UI thread.
It is the time consuming task the part that should be run in a AsyncTask, then this task can save the progress status in a volatile variable and then the UI thread can periodically update the progress bar reading the volatile variable, for example using a timer.
You can read all about AsyncTask here: https://developer.android.com/reference/android/os/AsyncTask.html
But here's my quick example/tutorial:
private class MyAsyncTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// prepare your UI for the background task beginning
}
#Override
protected Void doInBackground(Void... params) {
// do some long-running task...
// you can do partial updates like:
publishProgress(25);
/* more hard work */
publishProgress(50);
/* even more hard work */
publishProgress(75);
// and when you're done...
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// update your UI with the current progress (values[0])
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// update your UI now that it's done
}
}
The key concept to understand regarding AsyncTask is that every method except doInBackground() is executed on the UI thread (the main thread). That means you are free to update your UI from these calls.
doInBackground(), however, is executed on a different thread. That means you can do expensive work here without slowing down your app's user interface.
Of course, all the hard work you're doing on that background thread needs to make its way to the UI thread somehow (so that you can use it). That's what publishProgress() and the return statement of doInBackground() are for. When you call publishProgress(someValue), the system will invoke onProgressUpdate(someValue) for you. When you return someValue, the system will invoke onPostExecute(someValue) for you.

Loading until datas are available

I'm making an application, which only pick some datas on a website. But the problem is that the layout does not show up until the datas are available, the application seem to be blocked while it is looking for the datas. I tried to put the content view in the oncreate and then change the text in the onstart, when I have the datas, but the application still blocks.
Is this possible to print a default text, and then change it when the application have the datas?
Try this, it uses AsyncTask:
public class LoadData extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
//declare other objects as per your need
#Override
protected void onPreExecute()
{
//show loading dialog
progressDialog= ProgressDialog.show(YourActivity.this, "Progress Dialog Title Text","Process Description Text", true);
//do initialization of required objects objects here
};
#Override
protected Void doInBackground(Void... params)
{
//do loading operation here
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressDialog.dismiss();
};
}
You can call this using from your onCreate():
LoadData task = new LoadData();
task.execute();
Have you tried AsyncTask to download data from website (API)? It will show you progressdialog until data is not downloaded.

How to make asynctask work properly

I have a button on my app, if the user click it, it will refresh the current page by calling onResume(), and there are lots of database operations in onResume(). Instead of keeping the button stay pressed for a while, I would like to use asynctask to make a progressdialog while loading the data. But the problem is that the button will still be in pressed state and the progressdialog only show at the end of the operation for a very short duration.
RefreshButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
onResume();
}
});
protected void onResume()
{
doneloading = false;
monResumeloading = new onResumeloading();
monResumeloading.execute();
....loading...
doneloading = true;
}
private class onResumeloading extends AsyncTask<Integer, Integer, String>
{
private ProgressDialog progressDialog;
#Override
protected void onPostExecute(String result)
{
progressDialog.dismiss();
}
#Override
protected void onPreExecute()
{
progressDialog = new ProgressDialog(StatisticsActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
Log.i(TAG, " doneloading=false");
}
#Override
protected void onProgressUpdate(Integer... values)
{
}
#Override
protected String doInBackground(Integer... params)
{
while(!doneloading)
{
publishProgress(0); //dummy
log.i(TAG, "loading");
}
return null;
}
}
I observed that the "loading" log is showing right after the asynctask execution and stop right after the boolean doneloading becomes false. But the progressdialog is not working properly. Please help me :(
First thing, I don't think you should be calling your AsyncTask in the onResume() function. You can simply call it from your ClickListener.
Right now, you are doing your '....loading...' code before you even execute your AsyncTask. That's why the button stays pressed while it's executing '....loading...' and then when it's done, it executes your AsyncTask which really isn't doing anything - that's why it just shows up for a short duration.
Move your '....loading...' code into your doInBackground() of your AsyncTask and it should work ok.
Summary:
Click: Execute AsyncTask
AsyncTask: opens ProgressDialog
AsyncTask: Executes your '...loading...' code
AsyncTask: Wait for '...loading...' code to complete while still displaying dialog.
AsyncTask: Dismiss ProgressDialog

Display "Loading : Progress Bar " in Android Intent till Data Load

I am working on an android app, in that app i have intent2 which on click redirects to intent3 and takes some time then loads a table and displays server data into it.
Sometimes if there is a lot of data, it tales pretty much time to get the dataload and the time blank screen is displayed increases.
i wish to show a loading bar till the data loads.
how can i show the ProgrssBar till only when data is not displayed ?
Probably your best bet would be to use AsyncTask in your "intent3":
You could do it like this:
private class performBackgroundTask extends AsyncTask <Void, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(ClassName.this);
protected void onPreExecute()
{
Dialog.setMessage("Please wait...");
Dialog.show();
}
protected void onPostExecute(Void unused)
{
try
{
if(Dialog.isShowing())
{
Dialog.dismiss();
}
// do your Display and data setting operation here
}
catch(Exception e)
{
}
#Override
protected Void doInBackground(Void... params)
{
// Do your background data fetching here
return null;
}
}
You probably need to run an AsyncTask on onCreate when you open the new activity, the structure of the asynctask would be like this (taken from the google doc), notice that if you want to increament a progress bar you have to implement onProgressUpdate and call publishProgress in the doInBackground method
private class DownloadFilesTask extends AsyncTask<Void, Integer, Void> {
protected void onPreExecute()
{
// show your progress bar
}
protected Void doInBackground(Void... params) {
// do your work and publish the progress
publishProgress(progress);
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Void result) {
//dismiss your progress bar
}
}
This code is just an example, of course you need to adapt it to your logic/code.
Check out this simple and complete example

Fetching data from Internet in background and showing ProgressDialog or ProgressBar

I am developing an application which require accessing a website for
data, and will show that data on device. I wants to fetch data from
Internet in background and show ProgressDialog or ProgressBar on
device and when application receive response from server app will
dismiss the dialog or bar and will show data .
For this i am using AsyncTask -
code for AsyncTask is as follows--
ServerTask extends AsyncTask {
#Override
protected void onPreExecute() {
dialogAccessingServer = new ProgressDialog(ctx);
dialogAccessingServer.setMessage(shownOnProgressDialog);
dialogAccessingSpurstone.show();
}
#Override
protected ServerResponse doInBackground(String... urlArray) {
String urlString = urlArray[0];
HttpResponse serverResponseObject = null;
//finding HttpResponse
return serverResponseObject;
}//end of doInBackground
#Override
protected void onPostExecute(HttpResponse serverResponseObject){
dialogAccessingSpurstone.dismiss();
}
}
and calling this code as follows--
ServerTask serverTaskObject = new ServerTask();
serverTaskObject.execute();
HttpResponse response = serverTaskObject.get();
//performing operation on response
but ProgressDialog is not shown.(I guess the reason for it is the
thread is not complete and android invalidate only when thread has
completed).
My Questions --
1- If my guess is right ? If yes then how I should implement it?
2- If there is any other better way to do this?
thanks
Following is a template code that displays a ProgressDialog while a task is executing in background:
class GetTask extends AsyncTask<Object, Void, String>
{
Context mContext;
ProgressDialog mDialog = null;
GetPhotoFeedTask(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mDialog = new ProgressDialog(mContext);
mDialog.setMessage("Please wait...");
mDialog.show();
}
#Override
protected String doInBackground(Object... params)
{
// do stuff in background : fetch response
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setProgressBarIndeterminateVisibility(false);
// mDialog.dismiss();
}
}
and you invoke it from your activity using new GetTask(this).execute() statement;
Note: Note that while displaying a ProgressDialog if the user switches the Orientation or causes event that ensues one, the code might break. It is advised to use Managed Dialogs for such cases.
If there is some pending work on UI thread 'Progress dialog' will not appear, so dialog.show() should be the last line on UI thread and any further work should be done in onPostExecute() method.

Categories

Resources