I made a AsyncTask class with the following code
public class removeDialog extends AsyncTask<Void, Void, Void> {
Context c;
ProgressDialog asyncDialog;
String page;
public removeDialog(Context c, String page) {
this.c = c;
this.page = page;
asyncDialog = new ProgressDialog(c);
}
#Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setTitle("Please wait");
asyncDialog.setMessage("Loading...");
asyncDialog.setCancelable(false);
//show dialog
asyncDialog.show();
if (page == "algemeneVoorwaarden") {
Intent intent = new Intent(c, algemeneVoorwaarden.class);
c.startActivity(intent);
}
if (page == "contact") {
Intent intent = new Intent(c, contactTest.class);
c.startActivity(intent);
}
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
//don't touch dialog here it'll break the application
//do some lengthy stuff like calling login webservice
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();
super.onPostExecute(result);
}
}
First time I tried:
on the first time I see an ProgressDialog, but the second time I want to open the activity I get nothing.
Second time I tried:
I get no ProgressDialog even the first time I try.
I execute my code in an AsyncTask class, code:
voorwaarden.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new removeDialog(c, "algemeneVoorwaarden").execute();
}
});
Does someone know why it isn't working? Please help me.
Your dialog will be dismissed as soon as it's shown, because your doInBackground is empty. Try adding a Thread.sleep() with a few seconds, just to simulate a delay.
Also, I suspect that the new activities you're starting will leave your dialog behind. So I would suggest you to test the code without these new activities for now.
public class RemoveDialog extends AsyncTask<Void, Void, Void> {
ProgressDialog asyncDialog;
public RemoveDialog(Context c) {
asyncDialog = new ProgressDialog(c);
}
#Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setTitle("Please wait");
asyncDialog.setMessage("Loading...");
asyncDialog.setCancelable(false);
//show dialog
asyncDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(3000);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();
super.onPostExecute(result);
}
}
Related
I tried to change the orientation of my device on recycler view but it always crashes when progress dialog shows up.
How to solve this?
Here is my code:
private class LoadOrdersListAgent extends AsyncTask {
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(OrdersActivity.this);
ordersList = new ArrayList<>();
rvor = findViewById(R.id.recycler_view_orders_agent);
emptytv = findViewById(R.id.empty_view_orders_agent);
emptytv.setVisibility(View.GONE);
rvor.setHasFixedSize(true);
rvor.setLayoutManager(new LinearLayoutManager(OrdersActivity.this));
rvor.setItemAnimator(new DefaultItemAnimator());
dialog.setMessage("Loading....");
dialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
final OrdersAdapter adapter = new OrdersAdapter(getApplicationContext(), ordersList);
rvor.setAdapter(adapter);
rvor.setLayoutManager(new LinearLayoutManager(OrdersActivity.this));
srl.setRefreshing(false);
if (dialog.isShowing()) {
dialog.dismiss();
}
if (ordersList.isEmpty()) {
Log.d("TESTING.....", "LIST OF ORDERS ----->" + ordersList);
rvor.setVisibility(View.GONE);
srl.setVisibility(View.GONE);
emptytv.setVisibility(View.VISIBLE);
} else {
rvor.setVisibility(View.VISIBLE);
srl.setVisibility(View.VISIBLE);
emptytv.setVisibility(View.GONE);
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected Void doInBackground(Void... voids) {
ordersList = OrdersApi.getOrders(url, key);
return null;
}
}
private void swipeOrderLayout() {
srl = findViewById(R.id.swipe);
srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (new CheckNetworkUtil(OrdersActivity.this).isNetworkAvailable()) {
new LoadOrdersListAgent().execute();
// new LoadOrdersListAdmin().execute();
} else
Toast.makeText(OrdersActivity.this, "No Internet Connection!", Toast.LENGTH_SHORT).show();
srl.setRefreshing(false);
}
});
}
I got this error when i was Finishing/Destroying the activity without Dismissing progress Dialogue.
Solution use dialog.dismiss(); to dismiss the progress dialogue before destroying or pausing the activity
in your case remove the if condition and just call dialog.dismiss(); in postExecute method
Declare your ProgressDialog in Global using :
Add this code above onCreate() :
private ProgressDialog dialog;
Add this code within a onCreate():
dialog = new ProgressDialog(OrdersActivity.this);
dialog.setMessage("Loading....");
dialog.show();
Add this code within as onPreExecute method ,
if (!dialog.isShowing()) {
dialog.show();
}
I would like to make an app which displays some data from the server. When I log in as an admin, I would like there to be a progress dialog until the application gets all the data from the server.
I have 3 Classes. Main Activity(login screen), SecondActivity(displays data) and BackgroundWorker(which extends AsyncTask).
I know that in on postExecute I have to close ProgressBar
Override
protected void onPreExecute() {
if(activity.getClass() == MainActivity.class) {
this.progressDialog.setMessage("Please wait for a while.");
this.progressDialog.setTitle("Login");
this.progressDialog.show();
}
else
super.onPreExecute();
}
#Override
protected void onPostExecute(final String result) {
if(activity.getClass() == MainActivity.class) {
new CountDownTimer(1000, 500) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
System.out.println(result);
if (result.equals("Username or password is not correct")) {
alertDialog.setMessage(result);
alertDialog.show();
} else if(result.equals("is Admin")) {
Intent intent = new Intent(activity,Admin.class);
intent.putExtra("username",user);
activity.startActivity(intent);
activity.finish();
}
progressDialog.dismiss();
}
}.start();
}
I have made like this for login Screen but I don't think it is wise to delay the application on purpose. And also my implementation doesn't work if I call AsyncTask class twice in one activity. Any suggestion?
You can use this code:
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading");
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// Do your request
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pd != null)
{
pd.dismiss();
}
}
}
Take a look at this link, if you want!
Good luck with your android development!
I am new to android programming. I am developing a web crawler for which i am using a Async Task and it is working well.In order to keep user informed,i am using progress dialog. My problem is,if i use a Progress Dialog my program takes more time to execute and when i won`t use the progress dialog,it executes faster.
Done Work
OnCreate Method
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
Intent intent = getIntent();
s1 = intent.getStringExtra("Number1");
s2 = intent.getStringExtra("Number2");
s3=intent.getIntExtra("selectedItem",0);
HttpAsyncTask asyncTask = new HttpAsyncTask();
asyncTask.execute();
}catch (Exception e)
{
messageBox("Exception",e.getMessage());
}
}
Async Task Class
private class HttpAsyncTask extends AsyncTask<List<String>, Integer, List<String>> {
private ProgressDialog dialog;
#Override
protected void onPreExecute()
{
dialog = new ProgressDialog(Results.this);
dialog.setIndeterminate(true);
dialog.setMessage("Please Wait");
dialog.setCancelable(true);
dialog.show();
super.onPreExecute();
}
#Override
protected List<String> doInBackground(List<String>... urls) {
//android.os.Debug.waitForDebugger();
// spinner.setVisibility(View.VISIBLE);
List<String>resultList=new ArrayList<String>();
try
{
if(isCancelled())
return resultList;
resultList=WebCrawlerClass.GetPost(s1,s2,s3);
}catch (Exception e)
{
messageBoxs("Error", e.getMessage());
}
return resultList;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(List<String> result)
{
if(dialog.isShowing())
{
dialog.dismiss();
}
if(s3 == 2)
{
docListAdapter=new ListViewData(Results.this,result);
}
else {
docListAdapter = new NameNumListData(Results.this, result);
}
docList=(ListView)findViewById(R.id.listView2);
docList.setAdapter(docListAdapter);
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
super.onCancelled();
this.cancel(true);
}
}
Am I missing something? Need help..
Thanks and Regards,
Abhinav
In you activity
// Start the progress dialog
..
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// dismiss the progress dialog
}
};
HttpAsyncTask asyncTask = new HttpAsyncTask(handler);
asyncTask.execute();
In your asynctask class
private class HttpAsyncTask extends AsyncTask<List<String>, Integer, List<String>> {
private Handler handler = null;
public HttpAsyncTask (Handler handler) {
this.handler = handler;
}
protected Void doInBackground(Void... params) {
//Perform your task
// When you know that task is finished , fire following code
if (null != handler) {
Message message = handler.obtainMessage();
message.obj = Any data you want to sent to the activity
message.what = 1 ; ( Optional )
handler.sendMessage(message);
}
}
Thus when sendMessage function is called from doInbackground.. your handleMessage in your activity will get triggered and then you should dismiss the progress dialog
Hope this will improve the performance issue what you are facing
Remove super.onPreExecute(); in onPreExecute() method and check .It might Help
I was having some problem for Android activity transition. Basically what I am trying to do is share text to Twitter. However, when I open up the twitter content, it took quite a few seconds to load up the content and resulting in the white blank activity for a few seconds.
And here is my codes, when my button onClick, I am executing the loading dialog:
ivTwitterShare.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Thread newThread = new Thread() {
#Override
public void run() {
try {
super.run();
sleep(10000);
} catch (Exception e) {
} finally {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri
.parse(tweetUrl));
startActivity(intent);
progressDialog.dismiss();
}
}
};
newThread.start();
new LoadTwitterTask().execute();
}
});
private class LoadTwitterTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "Loading Twitter...",
"Retrieving Twitter information, please wait...", false,
false);
EventDialogueBox.customizeDialogueBox(context, progressDialog);
}
#Override
protected Void doInBackground(Void... params) {
try {
synchronized (this) {
int counter = 0;
while (counter <= 4) {
this.wait(50);
counter++;
publishProgress(counter * 25);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
}
}
However, my problem now is the white blank page before the content is loaded up still there. What I wanted is firstly, the loading dialog will show. Then, at the same time, the twitter intent is loading. Once finish loaded up the content, then dialog will be dismissed.
Any ideas?
Thanks in advance.
I am developing an feedback kind of application, when I click the "submitnow" button I am getting the following error
Activity has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView#46029dd0
Following is my code, please help me out.
public class SignOut_Activity extends SherlockActivity implements
OnClickListener {
Button btnSubmitNow, btnSubmitLater;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.signout);
((TextView) findViewById(R.id.tvSubTitle))
.setText(StoresListAdapter.StoreName);
btnSubmitNow = (Button) findViewById(R.id.btnSubmitNow);
btnSubmitLater = (Button) findViewById(R.id.btnSubmitLater);
btnSubmitNow.setOnClickListener(this);
btnSubmitLater.setOnClickListener(this);
progressDialog = new ProgressDialog(SignOut_Activity.this);
progressDialog.setMessage("Uploading data, please wait...");
}
#Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; finish activity to go home
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
// Set title
getSupportActionBar().setTitle("Sign Out");
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmitNow:
// Submit now
// Sample upload image
UploadImage.uploadImage("testimage");
new AsyncTask<Void, Void, Void>() {
// called before execution // main/UI thread
protected void onPreExecute() {
progressDialog.show();
};
#Override
protected Void doInBackground(Void... params) {
// Submit the store data
StoreData.postData(StoreList_Activity.storesList
.get(StoresListAdapter.Position));
return null;
}
// on store data uploaded // main/UI thread
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setSignOut();
StoreList_Activity.storesList
.get(StoresListAdapter.Position).isSubmitted = true;
SignOut_Activity.this.finish();
};
}.execute();
break;
case R.id.btnSubmitLater:
// Submit later
setSignOut();
StoreList_Activity.storesList.get(StoresListAdapter.Position).isSubmitLater = true;
VisitOps_Activity.isSubmitLater = true;
SignOut_Activity.this.finish();
break;
default:
break;
}
}
#SuppressLint("SimpleDateFormat")
private void setSignOut() {
VisitOp visitOp10 = new VisitOp();
visitOp10.setName("Sign Out");
visitOp10.setStatus("");
SampleData.visitOpsList.add(visitOp10);
if (VisitOps_Activity.VisitOps.SignOut == null)
VisitOps_Activity.VisitOps.SignOut = new SignOut();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
VisitOps_Activity.VisitOps.SignOut.SignOutTime = "Out: "
+ currentDateandTime;
}
}
Leak comes because you are keeping reference of activity after it destroyed also so use
if(progressDialog !=null)
{
progressDialog = null;
}
progressDialog = new ProgressDialog(this.getApplicationContext());
progressDialog.setMessage("Uploading data, please wait...");
OR
use this it will help
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmitNow:
// Submit now
// Sample upload image
UploadImage.uploadImage("testimage");
new AsyncTask<Void, Void, Void>() {
// called before execution // main/UI thread
protected void onPreExecute() {
progressDialog = new ProgressDialog(SignOut_Activity.this);
progressDialog.setMessage("Uploading data, please wait...");
progressDialog.show();
};
#Override
protected Void doInBackground(Void... params) {
// Submit the store data
StoreData.postData(StoreList_Activity.storesList
.get(StoresListAdapter.Position));
return null;
}
// on store data uploaded // main/UI thread
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setSignOut();
StoreList_Activity.storesList
.get(StoresListAdapter.Position).isSubmitted = true;
SignOut_Activity.this.finish();
};
}.execute();
Why this Error...?
this error happen when you keep reference of unused activity
Solution
remove reference of progress bar , dialog .....etc after use it .
by dismiss them or make them equal null
you can approach this when no longer need of it
Recommended put it in onStop
#Override
protected void onStop() {
super.onStop();
if(_dialog.isShowing()){
_dialog.dismiss();
}
if(_dialog != null){
_dialog = null;
}
}
Dismiss the dialog after its use, it won't let your application crash.
dialog.dismiss();
use that code progressDialog.dismiss();
Make sure you dismiss() the dialog, after dialog use and before any next background process to be initiated.