I have attached on click listener to a text view, inside on click listener a function say f1 is called and inside f1 another function say f2 is called.
Inside f2 I have created a android ProgressDialog object using current activity context, and called show function on progressDialog object. ProgressDialog takes time to appear on screen around 5-6 sec.
I have analyzed my code, but not able to understand why it takes this much time ?
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShowSyncDialog(); - f1
}
});
public void ShowSyncDialog()
{
fnSyncOfflineData(); - f2
}
public void fnSyncOfflineData()
{
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.show();
//other code
}
You should call your functions in an AsyncTask. Also ProgressDialog must be shown at the beginning of this works. Use something like this:
public class YourTask extends AsyncTask<String, Void, String> {
private Context mContext;
private ProgressDialog progressDialog;
public YourTask(Context context) {
super();
mContext = context;
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Your Message");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected String doInBackground(String... values) {
// If you want to use 'values' string in here
String values = values[0];
String yourResult = yourFunction();
return yourResult;
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
// Your task has done
...
}
}
Then call this task with:
new YourTask(YourActivity.this).execute();
You can change return type of task doInBackground method. This is just an example, you can search about AsyncTask.
Good luck.
Related
I am executing an AsyncTask from inside a DialogFragment but the progress bar is not shown during doInBackground. Here is the code:
public class GetCustomerSoapAsync extends AsyncTask<Void, Void, String>
{
ProgressDialog prg;
ActionBarActivity activity;
GetResponseFromGetCustomer listener;
public GetCustomerSoapAsync(ActionBarActivity activity, GetResponseFromGetCustomer listener)
{
this.activity = activity;
this.listener = listener;
prg = new ProgressDialog(activity);
prg.setMessage("Lütfen Bekleyin");
Log.i("ED","Progress will be shown");
prg.show();
}
#Override protected String doInBackground(Void... params)
{
//some stuff
}
#Override protected void onPostExecute(String s)
{
listener.getResponseFromGetCustomer(s);
if (prg.isShowing())
{
prg.dismiss();
}
}
and where I call it:
public class B1_PhoneNumberFragment extends android.support.v4.app.Fragment
{
...
buttonLogin.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
...
PhoneNumberVerified dialog = new PhoneNumberVerified();
dialog.show(getFragmentManager(), "NumberVerifiedByUser");
}
...
}
....
public class PhoneNumberVerified extends DialogFragment
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Format of this dialog will be changed
builder.setMessage("Numaranız doğru mu?\n" + "0" + number)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,
int id)
{
GlobalApplication.getUser().setPhone(
(excludeParanthesis
(number)));
//AsyncTask is not working properly,
// progress dialog is not shown and code flows before
// response is set to s
GetCustomerSoapAsync getCustomerSoapAsync =
new GetCustomerSoapAsync(
(ActionBarActivity) getActivity(),
new GetResponseFromGetCustomer()
{
#Override
public void getResponseFromGetCustomer
(String s)
{
response = s;
}
});
getCustomerSoapAsync.execute();
Log.i("ED", "Response after GetCustomerSoapAsync callback: " +
response);
}
And finally, maybe because of the flawed flow of the tasks or maybe something else, the callback can't do its job, and response is not set to return value of the AsyncTask.
Thanks for any help!
You should use onPreExecute :
class Task1 extends AsyncTask<Object, Void, String []> {
/** The Progress dialog. */
private final ProgressDialog dialog = new ProgressDialog(YourActivity.this);
/**
* Set the Progress dialog.
*/
protected void onPreExecute()
{
super.onPreExecute();
this.dialog.setMessage("Loading...");
this.dialog.show();
dialog.setCanceledOnTouchOutside(false);
}
protected String[] doInBackground(Object... params) {
///
}
protected void onPostExecute(String [] result)
{
super.onPostExecute(result);
this.dialog.dismiss();
}
}
To call it you should:
Task1 myTask = new Task1();
myTask.execute(stopArrey, start, end);
Hope it helped! :)
You need to operate on the ProgressDialog only on the UI Thread.
The constructor on the asynctask gives great flexibility enough to put the task in it's own class. Note: It's important that any field that is initialized in the Constructor on your custom AsyncTask takes advantage of the java final keyword so the field variables get automatic null for garbage collection.
Solution ProgressDialog code needs to be invoked in onPreExecute() where the task is still on the UI thread.
public class GetCustomerSoapAsync extends AsyncTask<Void, Void, String>
{
ProgressDialog prg;
// use final for fields initialized in a constructor.
final ActionBarActivity activity;
final GetResponseFromGetCustomer listener;
//The example below passes in the ProgressDialog from the caller where it's already shown. Pass it in to have access in the async tasks publish Progress method. Dismiss the ProgressDialog in the listener method; You didn't show your listener so this is just a technique
public GetCustomerSoapAsync(ActionBarActivity activity, GetResponseFromGetCustomer listener, ProgressDialog prg)
{
this.activity = activity;
this.listener = listener;
this.prg = prg;
// or move this code to onPreExecute() where it runs on the UI thread.
// move this code to onPreExecute()
//prg = new ProgressDialog(activity);
//prg.setMessage("Lütfen Bekleyin");
//Log.i("ED","Progress will be shown");
//prg.show();
}
Ok the issue I believe is you have to declare the PD in the layout visible to the user before the Aysnch task is executing.
For example:
//Declare the pd here. Pd private to class.
private ProgressDialog pd;
builder.setMessage("Numaranız doğru mu?\n" + "0" + number)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener()
{
....
pd = ProgressDialog.show(getActivity(), "",
"Your Message Here!!!", false);
// Now using a modified constructor call your execute function
//Previous parametes + pd
GetCustomerSoapAsync gCSA = new GetCustomerSoapAsync(...,...,pd);
getCustomerSoapAsync.execute();
}
Then in your Asynch class:
public class GetCustomerSoapAsync extends AsyncTask<Void, Void, String>
{
ProgressDialog prg;
ActionBarActivity activity;
GetResponseFromGetCustomer listener;
public GetCustomerSoapAsync(ActionBarActivity activity, GetResponseFromGetCustomer listener,ProgressDialog pd)
ProgressDialog prg;
{
this.activity = activity;
this.listener = listener;
this.prg = pd;
}
#Override protected String doInBackground(Void... params)
{
//some stuff
}
#Override protected void onPostExecute(String s)
{
listener.getResponseFromGetCustomer(s);
if (prg.isShowing())
{
prg.dismiss();
}
}
Ps: I don't know if you are using fragments as a implementation but if you are you must refer to the same pd you called in the onclick function in the fragment via rootview else you might be calling functions on a progresss dialog that never showed in the first place.
I seem to be going round in circles.
I have some code that even on a Galaxy S3 takes a few seconds to run. Drags data from database.
I want to add a progress bar popup (spinning circle) around this to give the user that the app is doing something.
I have tried Asyntasks elsewhere in app and work fine but for this type the main UI is not waiting for the Asyntask to finish before moving on and so the new activity that is called does not have all the data it needs and crashes.
Is AsyncTask the best way round this or is there an easier way to Puase the main Activity, show a progress bar and then move on once the long deley has been completed.
Thanks for time
UPDATE
public class UpdateDetailsAsyncTask extends AsyncTask<Void, Void, Boolean> {
private Context context;
private TaskCallback callback;
private ArrayList<Object> object;
private ProgressDialog progress;
public UpdateDetailsAsyncTask (
Context pContext,
ArrayList<Object> pObject,
TaskCallback pCallback) {
context = pContext;
callback = pCallback;
object = pObject;
}
#Override
protected void onPreExecute() {
Log.i("AsyncTask", "onPreExecuted");
progress = new ProgressDialog(context);
progress.setMessage(context.getResources().getString(R.string.loading));
progress.show();
}
#Override
protected Boolean doInBackground(Void... params) {
Log.i("Archery", "AsyncTask Excuted");
Log.i("Archery Scorepad", "Building Continue Round Details");
// Save Data to Database
return true;
}
protected void onPostExecute(Boolean result) {
Log.i("AsyncTask", "onPostExuted");
progress.dismiss();
callback.startNewActivity();
}
}
Task is called from main Activity
new UpdateDetailsAsyncTask(this, ArrayListOfObjects, this).exute();
UPDATE 2
..
UPDATE 3
The Code that does some work calls an a method within a Util Class which in calls a database class. I have log messages showing for all the rows of data I am saving to the database. It starts correctly and runs through it but the onPostExecute() appears to be called before the database method has completed.
Is my issue that I have nested classes within the activity and the task appears to have completed when the class below it has not?
Thanks
You must change to the next activity in onPostExecute from Asyntask
Yes!
Here is a simple code of AsuncTask
private class LoadImageAction extends AsyncTask<String, String, String>{
private Course course;
private ProgressBar pb;
public LoadImageAction(Course course, ProgressBar pb){
this.course = course;
this.pb = pb;
}
#Override
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onProgressUpdate(String... string){
}
#Override
protected void onPostExecute(String result){
}
}
You can run the action by
new LoadImageAction().execute();
I'm using "include" on my main layout. Each one of them is a RelativeLayout which needs an OnClick listener to be attached, and update some information related.
So I've tried to do it simply by:
setContentView(R.layout.allobjects);
ObjectListeners objectListeners = new ObjectListeners(objects);
for(int i=0;i<1;i++)
{
RelativeLayout objectBoxRelativeLayout = (RelativeLayout)findViewById(R.id.object1 + i);
objectBoxRelativeLayout.setOnClickListener(objectListeners.GetObjectListener(i));
SomeObject currentObject = this.objects.get(i);
Object viewObject = findViewById(R.id.object1 + i);
this.setObjectView(viewObject, currentObject);
}
The issue is that it takes too long after the "setContentView(R.layout.allobjects);" command, and the application shows black screen until it finish loading.
In addition, I use "setContentView(R.layout.allobjects);" after I perform the above commands. All of these commands have to be written after "setContentView(R.layout.allobjects);".
How can I handle that kind of situation ? Do I have to use onPreExecute and implement AsyncTask ?
Yes, AsyncTask is good solution to show loading dialog while these commands being executed.
UPDATE:
Add this class under your onCreate() function:
private class MyTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private Context context;
public MyTask(Activity activity) {
context = activity;
dialog = new ProgressDialog(context);
}
protected void onPreExecute() {
dialog.setTitle("Loading...");
dialog.setMessage("Loading...");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
//do your code here in background
protected void onPostExecute(Void res) {
dialog.dismiss();
}
}
then use the task inside onCreate() like this:
MyTask mt = new MyTask(this);
mt.execute();
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
I have been searching for an answer for this for some time now. I have an async task that downloads the database needed for my app, while this is downloading my app cant do anything as all the data it references is in this file, i have the app waiting for the file to be downloaded but i am attempting to show a progress dialog so the user knows something is happening while they wait for this to happen.
my code is currently
public class fileDownloader extends AsyncTask<Void, Integer, SQLiteDatabase>
{
private File dbFile;
private ProgressDialog progressDialog;
private Context context;
private SQLiteDatabase database;
private SQLiteDatabase.CursorFactory factory;
public fileDownloader(Context c)
{
super();
context = c;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(this.context);
progressDialog.setMessage("Downloading Database...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected SQLiteDatabase doInBackground(Void... v)
{
....
}
#Override
protected void onPostExecute(SQLiteDatabase db1)
{
progressDialog.dismiss();
}
however nothing shows up i have also tried directly calling ProgressDialog.show in the pre execute and moving this to the calling activity with no luck.
please help!
the solution to this was to look at the calling class the UI thread was getting blocked therefor the dialog never showed up.
Hmm - how long does your doInBackground method run? Maybe your dialog is shown, but the time is just too fast for the dialog to show up...
Below code is working fine, I am using it:
private class DownloadHomeSectionData extends
AsyncTask<Void, Void, Boolean> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(mainScreen);
progressDialog.setMessage(getResources()
.getString(R.string.loading));
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
for (HomeButton homeBtn : appDesigner.getHomeButtons()) {
StorageManager.getInstance().downloadFileSyncronously(
homeBtn.getTab_logo_selected_image());
StorageManager.getInstance().downloadFileSyncronously(
homeBtn.getTab_logo_unselected_image());
}
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
In your case, I think you may be passing wrong context to ProgressDialog.