Fetching data from Internet in background and showing ProgressDialog or ProgressBar - android

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.

Related

ProgressDialog show too much late with Asynch task in Android

I am new in android. I am trying to display ProgressDialog when click on button .
This is my code:
// set listener
btn_Login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//progress.show();
MyAsynch asynch = new MyAsynch();
asynch.execute();
}
In this code progress dialog too much late appear when i am comment on Asynctask object then progress dialog appear normally.
I am puting my progress dialog in
AsynchTask method
onPreExecute() but same out put dialog display late .
How to solve my problem..??
I am also read stack answers following link but not solve my problem .
async task progress dialog show too late
ProgressDialog appears too late and dissapears too fast
here is my Asynctask code
private class MyAsynch extends AsyncTask<String, Void, String> {
ProgressDialog progress;
String login_stat;
String stat;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(this);
progress.setTitle(" User Login ");
progress.setMessage("Please Wait!!");
progress.setCancelable(false);
progress.setIndeterminate(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
}
#Override
protected String doInBackground(String... urls) {
try {
login_stat = s_ApiHandling.doLogin(m_Et_Username.getText()
.toString().trim(), m_Et_Password.getText()
.toString().trim());
} catch (Exception e) {
System.out.println("internet connection loss ");
stat = "ERORR";
e.printStackTrace();
}
return stat;
}
#Override
protected void onPostExecute(String status) {
progress.dismiss();
}
}
You are probably doing too much in onPreExecute
Remove progress.cancel() from your doInBackground method and put it in to a onPostExecute method in your AsyncTask (like the second link you posted)
You shouldn't have anything talking to the UI in a background thread - that should all be done in pre/post execution.
you code should look like this:
AsyncTask<String, Void, String>()
{
private ProgressDialog progressDialog = ProgressDialog.show(this, "", "Loading...");
#Override
protected void onPostExecute(String result)
{
progressDialog.dismiss();
}
#Override
protected String[] doInBackground(String... params)
{
//ALL CODE GOES HERE.
}
}
When you call the asynctask you must not use the get() method or the progress dialog won't work correctly.

UI delayed showing with asynctask

I defined an AsyncTask in a button's onclicklistener, and once user clicks the button, ideally progress dialog shows while asynctask downloading.
However, progress dialog just flashes in and disappears before the results returned, and the button gets focused while the asynctask works in the background.
Can someone help me figure out what I did wrong here? Code snippet:
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
((Button)findViewById(R.id.buttonLoginActivity)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AsyncTask<Void, Void, Void> downloadTask= new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
String data = Service.getSomeData();
context.getContentResolver.notifyChange("content://some_url");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(progressDialog== null) return;
if(progressDialog!=null) {
progressDialog.dismiss();
progressDialog = null;
}
}
};
progressDialog.show();
downloadTask.execute();
try{
downloadTask.get();
}catch(Exception e){
e.printStackTrace();
return;
}
}
});
Don't use get()
downloadTask.get();
this is a blocking call. From the Docs
Waits if necessary for the computation to complete, and then retrieves its result.
Just use execute() as you are then do what you need with the results in onPostExecute()
show the progressDialog on the onPreExecute which need to be writen, and it will run on the UI thread, not in background ( android 4 )
also I would call the async task on a new Handler().post(myAsynctaskcaller)
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}

AsyncTask not showing the ProgressDialog

I am using an AsyncTask (which I am starting in my main activity) to load some data:
Context context = VehicleTabView.this;
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
new LoadingVehicles(context, progressDialog).execute(null, null, null);
Here is the AsyncClass:
package com.example.schedule_vehicles;
import com.example.utils.VehicleNames;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
// Showing a ProgressDialog once loading the list of vehicles is completed using an AsyncTask
public class LoadingVehicles extends AsyncTask<Void, Void, Void> {
Context context;
ProgressDialog progressDialog;
public LoadingVehicles(Context context, ProgressDialog progressDialog) {
this.context = context;
this.progressDialog = progressDialog;
}
#Override
protected void onPreExecute() {
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
new VehicleNames(context);
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
The problem that the ProgressDialog is not showing on the screen.
I type Log.d, to see if the program is going through all the phases - onPreExecute, doInBackground, onPostExecute, and it is going through all the phases and doing the job that I need. But the ProgressDialog is not showing. I read a lot of information about this thing and it seems that the PRE and POST execute are started by the main thread, which is blocked by the DOINBACKGROUND method, and this is the reason not to see the ProgressDialog. I tried to find some answer how this is solved - but no success.
If anyone faced this, please share your experience. THANKS a lot!
You're passing the ProgressDialog to the Task, just show() it before you start the AsyncTask, not from within the AsyncTask.
Your code looks good to me. You are correct about your understanding of Asynctask and your use of them also appears correct.
The only thing that I can think of is that you must make sure that you are calling execute() on the UI Thread as well. From the code posted I'm not able to tell what context you are in.
Make sure you can pass in "this" as a context. That will tell you if your on the UI thread or not.
ProgressDialog progressDialog = new ProgressDialog(this);
Try :
ProgressDialog progressDialog = new ProgressDialog([Activity Name].this);
Let me know if this solves the problem or I'll see in depth.
Maybe you are missing the context.
ProgressDialog progressDialog = new ProgressDialog(this);
Normally when creating a ProgressDialog, you use the static method ProgressDialog.show(context, title, message). This will create and show the message and give you back a reference to the dialog.
onPreExecute and onPostExecute are called on the main thread, and are not blocked by the doInBackground, which runs on another thread. onPreExecute is called before doInBackground and onPostExecute is called after.
Here's some example code:
public static class InitializeTask extends MyAsyncTask<String, String, Response<Object>> {
private Activity activity;
private ProgressDialog dialog;
public InitializeTask(Activity activity) {
this.activity = activity;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(activity, null, "Initializing...");
}
#Override
protected void onPostExecute(Response<Object> result) {
if (dialog != null && dialog.isShowing())
dialog.dismiss();
}
#Override
protected Response<Object> doInBackground(String... params) {
}
#Override
protected void attach(Activity context) {
this.activity = context;
dialog = ProgressDialog.show(context, null, "Initialize...");
}
#Override
protected void detach() {
if (dialog.isShowing())
dialog.dismiss();
activity = null;
}
}
Attach and detach are my own methods for referencing a cross orientation changes.

ProgressDialog is not shown in the AsyncTask

Document doc = new Obtainer(context, uri).execute().get();
This code in the activity class renders the Obtainer(which extends AsyncTask) which gets the xml document from the url. This is the onPreExecute method:
protected void onPreExecute() {
super.onPreExecute();
System.out.println("Pre execute began");
exception = null;
dialog = new ProgressDialog(context);
dialog.setMessage("Loading started");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
System.out.println("Preexecute end");
dialog.show();
}
context is set in the Constructor:
public Obtainer(Context c, String addr) {
context = c;
address = addr;
}
During the runtime I can see in the console output both "Pre execute began" and "Preexecute end" but the progress dialog is not shown. What is the probleM?
Use this code, it works for me:
class Obtainer extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(App.this); // App - your main activity class
dialog.setMessage("Please, wait...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// ...
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
And in your main activity class method call
new Obtainer().execute();
What Context are you passing when you create your Obtainer (AsyncTask subclass)?
If you are using the Application context via getApplicationContext(), it can not be used to create a Dialog (or any View for that matter). You need to pass it a Context that can create Views.
"If you're in the habit of using your application context (from a call to getApplicationContext(), for example) in places where you need a Context to create views, it's only a matter of time until you find a case where things don't work quite like you would want or expect."
From: https://plus.google.com/107708120842840792570/posts/VTeRBsAeyTi

How can I dismiss ProgressDialog in AsyncTask

I am using a ProgressDialog to be shown while my background process goes on, but after background process is completed the ProgressDialog is not dismissed still.
Here is my code
private class async extends AsyncTask<String, Void, Boolean> {
final ProgressDialog progressDialog = new ProgressDialog(getParent());
#Override
protected Boolean doInBackground(String... params) {
GetJson json = new GetJson();
boolean success = false;
JSONObject mJsonObject = json
.readJsonObject("url");
try {
success = mJsonObject.getBoolean("success");
} catch (Exception e) {
}
return success;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
}
#SuppressWarnings("static-access")
#Override
protected void onPreExecute() {
progressDialog.show(getParent(), "Working..", "Please wait...");
}
}
private final class YourTask extends AsyncTask<Void, Void, Object> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(YourActivity.this, "Title", "Message", true);
}
#Override
protected Object doInBackground(final Void... params) {
// Doing something
}
#Override
protected void onPostExecute(final Object result) {
// Check result or something
dialog.dismiss();
}
}
You can call progressDialog.dismiss() in your AsyncTask's onPostExecute() method.
In onPostExecute() method call dismiss() on your dialog.
I dont know, if you solved this problem, probably yes.
But for next users what will have the same problem (i had it right now too)..
The problem is in your declaration.
final ProgressDialog progressDialog = new ProgressDialog(getParent());
or in your "second" declaration
progressDialog.show(getParent(), "Working..", "Please wait...");
Because in the first one you put in there the getParent parameter (probably MainActivity.this)
and the same you do in calling show method.
Therefore is there 2 parents.. and if you call dismiss() in post execute..it dismiss the first one..but not the another one what have then dialog.isShowing() equal to false.
So important is have there just 1!!!!! parent content..so you can assign the content in declaration with:
new ProgressDialog(content);
or you can do
ProgressDialog dialog=new ProgressDialog();
dialog.setMessage("Loading");
dialog.show(getParent());
and then dismiss it and everything is allright.
or you can do:
ProgressDialog dialog=new ProgressDialog(getParent());
dialog.setMessage("Loading");
dialog.show();
but never give in there twice parents, contents, whatever..
AsyncTasks should not handle at ALL a dialog. Dismissing the dialog in the PostExecute phase can easily lead to an IllegalStateException as the underlying activity can already be destroyed when the dialog gets dismissed. Before destroying the activity the state of the activity will be saved. Dismissing the dialog afterwards will lead to an inconsistent state.

Categories

Resources