Android Async task not working - android

I am calling this from a function by creating an object.The progress box appears and then disappears but the toast is not displayed.(I have removed the code that follows the toast but even that code which queries the web page is not executed in the doinBackground)
private class MyTask extends AsyncTask<Void, Void, Void> {
MyTask(String p) {
enter=p;
}
protected void onPreExecute() {
progressDialog = ProgressDialog.show(CheckitoutActivity.this,"", "Loading. Please wait...", true);
}
protected Void doInBackground(Void... params) {
try {
Toast.makeText(getApplicationContext(), "GHJGFHGJL",1000).show();
}
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
The doInBackground does not apppear to be called. Even the toast is not displayed.Why is that.

you can not display the UI like toast and dialog alert in doInBackground method. instead you can show these UI in postExecute method of asynkTask

Toast (You can't touch UI Thread from doInBack() that's why) is not works in doInBackground() so just put Log
protected Void doInBackground(Void... params) {
try
{
Log.e("AsyncTask","Inside the doInBackground()");
}
}
Now check your logcat... If ProgressDailog is showing then your AsyncTask is works well.

doInBackground method is non UI thread so it can't dispaly a toast
So use runOnUIthread(this) or onProgressUpdate and are sure .execute() with
object, like objMytask.execute();

Related

Showing progressbar in listview while downloading

There's a "download" button in each listview item. While the button is clicked, it will start a worker thread to down files. And at the same time, the button changed to progressbar and showing the progress rate.
So please show me some proper ways.
Use an AsyncTask since it has special methods for communicating with the main (UI) thread despite being asynchronous.
Here is an example:
http://android-er.blogspot.com/2010/11/progressbar-running-in-asynctask.html
Something like this:
public class DownloadTask extends AsyncTask<Void, Void, Boolean> {
protected void onPreExecute() {
ProgressDialog() progress = new ProgressDialog(context);
progress.setMessage("Loading ...");
progress.show();
}
protected Boolean doInBackground(Void... arg0) {
// Do work
return true;
}
protected void onPostExecute(Boolean result) {
progress.dismiss();
}
}
This should be nested in your activity class and executed like this:
new DownloadTask().execute();
You will likely need to adjust the asynctask to fit your needs but this will get you started.

How to properly implement a progressBar in Android?

Now I am doing an Android application.In my application I have to get the data from json page.This operation is taking time delay.So I have to show a progressbar until the fetching process is completed.I used the following code to show progressbar.
public void onCreate(Bundle savedInstanceState) {
//somecode
ProgressDialog progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("Loading");
progressBar.show();
Thread thread = new Thread(this);
thread.start();
}
public void run() {
flag=GetFixtureDetailsJsonFunction();
handler.sendEmptyMessage(0);
}
protected boolean GetFixtureDetailsJsonFunction() {
//json parsing code
return true
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (flag==true) {
progressBar.dismiss();
}
}
};
Using this code I am getting exception.android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
AsyncTask is best way for getting response from xml or database. try like this,
private class DownloadQuestion extends AsyncTask<String, Void, String>
{
#Override
protected void onPreExecute()
{
pd = ProgressDialog.show(Activity_SplashScreen.this, "","Please wait...", true,false);
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls)
{
//Write background code here Code
return "";
}
#Override
protected void onPostExecute(String response1)
{
//Some Code.....
if (pd != null && pd.isShowing())
pd.dismiss();
}
}
Instead i would suggest you to implement AsyncTask, which is known as Painless Threading in android.
Using this AsyncTask, you don't need to bother about managing Threads. And its easy!!
FYI, do as follows:
Display ProgressBar in onPreExecute() method.
Do long running tasks inside the doInBackground() method.
Dismiss the ProgressBar inside the onPostExecute() method. You can also do display kinds of operation in this method.
This is a bit strange way to implement this functionality. Instead of fixing that code I suggest you using AsyncTask, which was implemented right for that purpose. See here.
You are trying to access the UI View from another thread which is not eligible.In this case this is your handler.
Instead of trying to access UI thread like this you should use an AsyncTask and do your progressDialog logic in it.
Start showing the progress bar onPreExecute
doInBackground() jobs while progressBar showing
And finallly dismiss your progressBar after your doInBackground() is complete onPostExecute()

Android Progress Dialog not showing until the function finish running (AsyncTask)

When a button is clicked I'm calling the async class in a function and I need to show progressDialog until it runs the displaylist function. But it shows up only after the function finished running and closes immediately. Please help me what am I doing wrong here.
public class FilterAsyncTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dispProgress;
#Override
protected void onPreExecute()
{
dispProgress = ProgressDialog.show(Filter.this, "Please wait...",
"Loading...", true, true);
}
protected Void doInBackground(Void... params) {
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
MerchantsActivity.displayList();
dispProgress.cancel();
finish();
}
}
Your AsyncTask will complete immediately because you do exactly nothing in doInBackground()! That's where your long-running background non-UI code is supposed to go...
I would recommend you not to use the static ProgressDialog#show method. Rather donew ProgressDialog() and initialize it accordingly and finally call show(). I have never used the static method and do not know how it works, but I have used the other option. Furthermore the static method seems to have no available documentation.

ProgressDialog not shown when AsyncTask.get() called [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
AsyncTask block UI threat and show progressbar with delay
I want to show a progressDialog while retrieving JSON from any server. So I had used AsyncTask as a solution (not sure any different way out).
Everything is fine, the ProgressDialog works properly until I call .get() method using AsyncTask instance. I suppose it's blocking UI somehow. Here is my AsyncTask:
public class myAsync extends AsyncTask<String, String, List> {
String message; // for dialog message
ProgressDialog progress;
Intent myIntent;
Context ctx;
public myAsync(String message, Context ctx) {
this.message = message;
this.ctx = ctx;
progress = new ProgressDialog(ctx);
}
#Override
protected void onPreExecute() {
progress.setMessage(message);
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
}
#Override
protected List doInBackground(String... params) {
//returns any list after the task
return anyList;
}
#Override
protected void onPostExecute(List result) {
if(progress.isShowing())
progress.dismiss();
}
}
And here is myActivity which is calls AsyncTask:
myAsync asyncTask = new myAsync("Loading...", this);
asyncTask.execute("Any string", "Other string");
asyncTask.get(); // If I comment out this line, ProgressDialog works
After execute, when I tried to log the result from doInBackground and onPostExecute both there is no problem. But if I want to get with .get() the result ProgressDialog is not shown or shown so little time (maybe 0.2 seconds)
What's the problem?
Yes, get() waits if necessary for the computation to complete, and then retrieves its result. This means, that you are blocking your UI thread, waiting for the result.
Solution: Don't call get
Usually, you will call a function (callback) in the postExecute.
Calling .get() changes your AsyncTask into an effective "SyncTask" as it causes the current thread (which would be the UI thread) to wait until the AsyncTask has finished its processing. Since you are now blocking the UI thread the call to the ProgressDialog's .show() method never gets a chance to allow the dialog to draw itself the screen.
Removing the call will allow it to run properly in the background.
If you need to do processing after the task has completed I suggest you either put it inside the onPostExecute method itself or use a callback to the Activity from onPostExecute.
If I understand your question correctly, you need to update the progress of your AsyncTask in a ProgressDialog and this isn't currently working. So a couple of things to note: I'm not sure what you're trying to achieve with .get() but I'll assume you want to display the progress.
I've modified your program below to update the UI thread with your AsyncTask's progress. Everytime you need to update the progress, update that prog variable in the doInBackground method.
public class myAsync extends AsyncTask<String, Integer, List> {
String message; // for dialog message
ProgressDialog progress;
Intent myIntent;
Context ctx;
public myAsync(String message, Context ctx) {
this.message = message;
this.ctx = ctx;
progress = new ProgressDialog(ctx);
}
#Override
protected void onPreExecute() {
// Runs on the UI thread
progress.setMessage(message);
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
}
#Override
protected List doInBackground(String... params) {
// Runs in the background thread
// publish your progress here!!
int prog = 5; // This number will represent your "progress"
publishProgress(prog);
return anyList;
}
protected void onProgressUpdate(Integer... progress) {
// Runs in the UI thread
// This method will fire (on the UI thread) EVERYTIME publishProgress
// is called.
Log.d(TAG, "Progress is: " +progress);
}
#Override
protected void onPostExecute(List result) {
// Runs in the UI thread
for (int i=0; i<result.size(); i++) {
Log.d(TAG, "List item: " + result.get(i));
}
if(progress.isShowing())
progress.dismiss();
}
}
Try using runOnUiThread like this:
runOnUiThread(new Runnable(){
public void run() {
dialog.show();
}});
Running something on a AsyncTask means that its running away from the UIthread so usually you cant run ui operations from inside Async methods without handlers and stuff which I usually stay away from. I also handle such a solution by creating a progressDialog as a variable in my class above my oncreate so its visible to the whole class. I then call the progressdialog right before my asynctask and then since its visible to the whole class I call .dissmiss() in the onPostExecute

AsyncTask not locking main thread?

I'm using following code to fill a custom ListPreference dialog. Since the fill procedure takes a lot of time i want to show a progress dialog during the fill procedure.
My problem is that filler.execute() does not block onPrepareDialogBuilder and functions goes till the end before values are filled causing an exception... Any idea?
#Override
protected void onPrepareDialogBuilder(Builder builder) {
// Load data
if (this.getEntries()==null) {
FillerTask filler = new FillerTask();
filler.execute();
}
Log.d(TAG, "Filler finished");
super.onPrepareDialogBuilder(builder);
}
Here is Filltertask code, basically he looks for every activity with a MAIN Intent filling a list:
private class FillerTask extends AsyncTask<Void, Void, String[][]> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
Log.d(TAG, "Dismiss dialog");
dialog = ProgressDialog.show(MyListPreference.this.getContext(), "", "Doing stuff...", true);
}
#Override
protected String[][] doInBackground(Void... params) {
return fill();
}
public String[][] fill() {
Log.d(TAG, "Fill started");
CREATE LISTS...
// Done
Log.d(TAG, "Fill done");
String[][] result = new String[][] {entryNames, entryValues};
return result;
}
#Override
protected void onPostExecute(String[][] result) {
Log.d(TAG, "Post execute");
MyListPreference.this.setEntries(result[0]);
MyListPreference.this.setEntryValues(result[1]);
dialog.dismiss();
}
}
My problem is that filler.execute() does not block onPrepareDialogBuilder and functions goes till the end before values are filled causing an exception... Any idea?
That is the entire point behind an AsyncTask. The "Async" in AsyncTask means asynchronous.
Use your AsyncTask to get your data. Then, in onPostExecute(), display the dialog.
Found the solution, best way to do this is override the onClick method and let the AsyncTask postExecute call the "super()", so click is not passed until content is loaded and during load progress bar is correctly displayed.
asyntask doesn't lock main thread, it just drops a message to message queue of main thread

Categories

Resources