I have a big process called that will be called when I execute http-request and move to other activity or fragment,
The problem is, the process isn't finished yes then the display going to be blank and after that it move to another activity.
Question is, how we can set the timer and the timeout and where I can put the line code.
This is my current code
public class BigProccess extends AsyncTask<Void, Integer, Void> {
private Context mContext;
ProgressDialog mProgress;
private int mProgressDialog=0;
public BigProccess(Context context, int progressDialog){
this.mContext = context;
this.mProgressDialog = progressDialog;
}
#Override
public void onPreExecute() {
mProgress = new ProgressDialog(mContext);
mProgress.setMessage("Loading...");
// if (mProgressDialog== ProgressDialog.STYLE_HORIZONTAL){
mProgress.setIndeterminate(false);
mProgress.setMax(100);
mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgress.setCancelable(false);
// }
mProgress.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// if (mProgressDialog== ProgressDialog.STYLE_HORIZONTAL){
mProgress.setProgress(values[0]);
// }
}
#Override
protected Void doInBackground(Void... values) {
try {
//This is to simulate there is a heavy process is running
//and we make it slow down by 500 ms for each number
for (int i =1; i<=10;i++){
publishProgress(i*10);
Thread.sleep(500);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mProgress.dismiss();
// Toast.makeText(mContext,"Done!!!",Toast.LENGTH_LONG).show();
}
}
I've tried modified the thread.Sleep to 15000ms but it won't work.
Any help would be appreciated.
Related
I'm inserting some data in my app's local database inside AysncTask, but when executing the class the progress dialog is not showing on the screen while i can see the running log. I see many related answer but the issue is not resolved. I read the .get() method blocks the ui but I'm already not using this method. I don't why it is not showing on the screen
calling async class from main Activity
AsyncGetDataFromServer task = new AsyncGetDataFromServer(this);
task.execute();
code of AsyncTask class
public class AsyncGetDataFromServer extends AsyncTask<Void, Void, Boolean> {
ProgressDialog pd;
Context cxt;
DatabaseHandler dbHelper;
private static ArrayList<DataModel> categoryArrayList;
public AsyncGetDataFromServer(Context context) {
// TODO Auto-generated constructor stub
cxt= context;
pd = new ProgressDialog(cxt);
pd.setTitle("Please wait");
pd.setMessage("Loading...");
pd.setCancelable(false);
dbHelper = new DatabaseHandler(cxt);
}
#Override
protected Boolean doInBackground(Void... params)
{
try {
Log.d("do in background","true");
for (int i = 0; i < response.body().getVideoEntity().size(); i++) {
//inserting in categories
VideoEntity videoEntity;
videoEntity = response.body().getVideoEntity().get(i);
dbHelper.insertChannels(videoEntity);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("exception error", e.getMessage());
}
return true;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("on pre execute","true");
pd.show();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d("on post execute","true");
pd.dismiss();
}
}
pass Activity instead of context to the constructor.For example-
AsyncGetDataFromServer task = new AsyncGetDataFromServer(MyActivity.this);
task.execute();
You should implement the method onProgressUpdate and use the method publishProgress :
see https://developer.android.com/reference/android/os/AsyncTask.html
Show dialog in onPreExecute() method & dismiss in onPostExecute() method:
private class AsyncGetDataFromServer extends AsyncTask<Void, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(YourClass.this);
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.show();
}
protected void doInBackground(final Void unused) {
//don't interact with the ui!
}
protected void onPostExecute(final Boolean result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
So I am completely new to Andorid programming and can't seem to get a ProgressDialog to show on a ListActivity (ScheduleActiviy in my example) when running an AsyncTask from a separate class (GetGames in my example). I am attempting to use separate class for code re-usability. When I previously had the AsyncTask as an embedded class it seemed to work. I have posted what I believe to be all the relevant code. Any help would be great. Thanks!
ScheduleActivity.java
public class ScheduleActivity extends ListActivity
{
private final String PDIALOG_MSG = "Loading schedule...";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.schedule);
ArrayList<HashMap<String, String>> gamesList = null;
try
{
// Loading information in Background Threads
gamesList = new GetGames(ScheduleActivity.this, PDIALOG_MSG).execute().get();
GetGames.java
public class GetGames extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>>
{
private Context context;
private ProgressDialog pDialog;
private String pDialogMsg;
public GetGames(Context ctx, String dialogMsg)
{
context = ctx;
pDialogMsg = dialogMsg;
}
#Override
public void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage(pDialogMsg);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onPostExecute(ArrayList<HashMap<String, String>> rtnList)
{
pDialog.dismiss();
}
Your ProgressDialog should probably be controlled on the Activity level instead of the AsyncTask level. Theoretically I don't see why how you're doing it wouldn't work, but I can show you a method which definitely works (it's what I do) and it organizes things a bit differently:
//In AsyncTask
#Override
protected void onPreExecute() {
showProgressDialog(R.string.importing_pages);
}
#Override
public void onPostExecute(Boolean b) {
hideProgressDialog();
}
//In Activity
public void showProgressDialog(int msgResId) {
showProgressDialog(getString(msgResId));
}
public void showProgressDialog(String msg) {
mProgressDialog = ProgressDialogHelper.buildDialog(this, msg);
mProgressDialog.show();
}
public void hideProgressDialog() {
if(mProgressDialog != null)
mProgressDialog.dismiss();
}
//My progress dialog helper class:
public class ProgressDialogHelper {
/**
* Creates a generic progress dialog with the specified message
*
* #param activity the activity which hosts the dialog. This must be an activity, not a context.
* #param msgResId the resId for the message to display
* #return a progress dialog
*/
public static ProgressDialog buildDialog(Activity activity, int msgResId) {
return buildDialog(activity, activity.getApplicationContext().getString(msgResId));
}
/**
* Creates a generic progress dialog with the specified message
*
* #param activity the activity which hosts the dialog. This must be an activity, not a context.
* #param msg the message to display
* #return a progress dialog
*/
public static ProgressDialog buildDialog(Activity activity, String msg) {
ProgressDialog dialog;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
dialog = new ProgressDialog(new ContextThemeWrapper(activity, android.R.style.Theme_Holo_Dialog));
else
dialog = new ProgressDialog(activity);
dialog.setMessage(msg);
dialog.setCancelable(false);
return dialog;
}
}
You don't have to make a helper class if you don't want to, it's just how I organized it. The main idea here is that the progress dialog should be owned by the Activity instead of the AsyncTask.
Also, the context used must be the activity's, not getApplicationContext(). It looks like you have that part right though.
You can display Progress Dialogs using AsyncTasks. That's not a problem. I do it all the time. What may be the problem is the doInBackground() method. What do you have there?
I also generally nest the AsyncTasks within the Activity class, so that it can call other Activity class methods in the onPostExecute() method. Otherwise, in order for it to communicate back with your Activity you'll have to use something like a handler or static references.
public class TestActivity extends Activity {
private AsyncTask<Void, Void, ArrayList<String>> bgLoader;
private ArrayList<String> listOfStuff;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
listOfStuff = new ArrayList<String>();
textView = (TextView) findViewById(R.id.textView);
textView.setText("Your list has " + listOfStuff.size() + " items in it!");
bgLoader = new MyAsyncTask(this, "Waiting...").execute();
}
private void resumeDoingStuff() {
try {
listOfStuff = bgLoader.get();
textView.setText("Your list has " + listOfStuff.size() + " items in it!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public class MyAsyncTask extends AsyncTask<Void, Void, ArrayList<String>> {
private ProgressDialog progressDialog;
private String message;
private Context ctx;
public MyAsyncTask(Context context, String message) {
this.ctx = context;
this.message = message;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(ctx);
progressDialog.setMessage(message);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected ArrayList<String> doInBackground(Void... params) {
ArrayList<String> retList = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
try {
retList.add("TEST STRING " + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return retList;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
progressDialog.dismiss();
resumeDoingStuff();
}
}
}
The progress dialog in AsyncTask does not dismiss, even though progressDialog.dismiss is run in onPostExecute().
I have tried implementing many answers to related questions on SO, with no success so far.
I am sure that I must be overlooking something very basic, but I am stuck.
Any pointers to an explanation and code snippet would be great, Thanks.
Main
public class Main extends Activity {
String result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
asyncTask task = new asyncTask("Loading ...", this);
try {
result = task.execute("Question").get();
}
catch (Exception e) {
Log.e("Error: ", e.toString());
}
}
}
asyncTask
public class asyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private String message;
private Context context;
public asyncTask(String msg, Context ctx) {
this.context = ctx;
message = msg;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.show(context, "", message, true, false);
}
#Override
protected String doInBackground(String... params) {
int count = 100000;
for (int i = 0; i < count; i++) {
// waste time
}
return "Answer";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
Actually your are doing :
progressDialog.show(context, "", message, true, false);
instead it should be like :
progressDialog = ProgressDialog.show(context, "", message, true, false);
You have to statically call show method and assign it to your progressDialog
Make this changes in your onPostExecute
#Override
protected void onPostExecute(String result) {
try{
if(progrssDialog.isShowing()){
progressDialog.dismiss();
}
}
catch(Exception e){
e.printStackTrace();
}
finally
{
progressDialog.dismiss();
}
}
A common issue i have found is the Variable Scope.
Most times , the ProgressDialog will be defined inside a Method , which wont be accessable outside that method.
You need to Declare it like so ,
Public Class MainActivity extends Activity {
ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private class asyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}
replace
task.execute("Question").get();
with
task.execute("Question");
by calling .get() you forcing main thread to wait. It will/can hang your UI.
progressDialog.dismiss();
put this in doInBackground() method before Return Statement.
I've isolated an issue I am having when showing a ProgressDialog while an AsyncTask is executing and then trying to show an AlertDialog when onPostExecute is executed.
The steps to reproduce are:
1-Run the task
2-Before the task has finished press Home button
3-When you assume the task is finished return to the app
4-AlertDialog is not shown and a low bright (like disabled) screen is shown.
I've discovered that moving the dialog.dismiss() line to the end of the onPostExecute method fixes the problem... But this is weird, isn't it?
Source code:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickButton(View view) {
new MyAsyncTask(this).execute();
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialog;
Context ctx;
public MyAsyncTask(Context ctx) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(ctx);
dialog.setMessage("Loading");
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void value) {
dialog.dismiss();
AlertDialog.Builder alertbox = new AlertDialog.Builder(ctx);
alertbox.setNeutralButton("OK", null);
alertbox.setMessage("Message");
alertbox.setIcon(android.R.drawable.ic_dialog_alert);
alertbox.show();
// dialog.dismiss(); If I remove it from above and put this line here, it will work ok
}
}
}
I have a huge database (40MB) on an SDCard. I need fetch data, with LIKE in query, which is very slow.
DB request takes about 5 seconds. Therefore, I need to do it asynchronously and with ProgressDialog.
I tried it with AsyncTask, but problem is with ProgressDialog. It was implemented this way:
private class GetDataFromLangDB extends AsyncTask<String, String, String> {
private final ProgressDialog dialog = new ProgressDialog(TranslAndActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
urDBCursor.close();
curDBCursor = null;
scaAdapter = null;
this.dialog.setMessage("Loading data...");
this.dialog.show();
}
#Override
protected String doInBackground(String... whatSearch) {
String result = "";
if (myDatabaseAdapter != null) {
curDBCursor = myDatabaseAdapter.fetchAll(whatSearch[0]);
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
prepareListView();
}
}
The problem is that ProgressDialog is not shown during the DB request.
After finished database query, it flash on screen for a short time. When user tries
to tap on screen during database request, UI is freezed, and after DB request
message about 'not responding' is shown.
I tried it with a thread this way:
public void startProgress(View view, final String aWhatSearch) {
final ProgressDialog dialog = new ProgressDialog(MyActivity.this);
if (curDBCursor != null){
curDBCursor.close();
curDBCursor = null;
}
dialog.setMessage("Loading data...");
dialog.show();
Runnable runnable = new Runnable() {
public void run() {
curDBCursor = myDatabaseAdapter.fetchAll(aWhatSearch);
// dirty trick
try {
Thread.sleep(250); // it must be here to show progress
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
public void run() {
if (dialog.isShowing()) {
dialog.dismiss();
}
prepareListView();
}
});
}
};
new Thread(runnable).start();
}
The result was the same, but when I used the trick with Thread.sleep(250);
ProgressDialog was shown during the database request. But it is not spinning,
it looks freezed during the DB request.
DB stuff is called this way (after tap on search button):
btnSearchAll.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// AsyncTask
new GetDataFromLangDB().execute(edtTextToSearch.getText().toString());
// or Thread
//startProgress(null, edtTextToSearch.getText().toString());
}
});
I found a lot of problems like this in SO, but nothing was useful for me.
Could it be that DB is on SD Card?
I put the definition of the dialog into the AsyncTask Class and it works fine for me.
Take a look at this exampel (You have to change NAMEOFCLASS in the name of your CLASS:
private class doInBackground extends AsyncTask<Integer, Integer, Void> {
final ProgressDialog dialog = new ProgressDialog(NAMEOFCLASS.this) {
#Override
protected void onPreExecute() {
dialog.setCancelable(false);
dialog.setTitle(getString(R.string.daten_wait_titel));
dialog.setIcon(R.drawable.icon);
dialog.setMessage(getString(R.string.dse_dialog_speichern));
dialog.show();
}
#Override
protected void onCancelled() {
dialog.cancel();
}
....
#Override
protected void onProgressUpdate(Integer... values) {
// DO YOUR UPDATE HERE
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
Maybe this SO answer could help you. It looks like similar problem. Try to use AsyncQueryHandler for querying your database
declare you Dialog box on Class (Activity) level like this
private ProgressDialog dialog = null;
show the progress dialog and call the AsyncTask class when you want to start you Busy work..like onButton click or any
dialog = ProgressDialog.show(this,"Sending Email to your account please! wait...", true);
SendingEmailTask task = new SendingEmailTask();
String s = "";
task.execute(s);
create your inner class like
private class SendingEmailTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
//do your work here..
// like fetching the Data from DB or any
return null;
}
#Override
protected void onPostExecute(String str) {
//hide progress dialog here
dialog.dismiss();
}
}
let me know if this help!!