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
Related
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 have a class called RestClient that gets some information from my webService and then return and I'm trying to make a Progress dialog run while it is accessing the internet. And as I use this class in more than one place I won't make in the Activity itself. Here is my RestClient class:
public class RestClient extends AsyncTask<URL, String, String> {
private Context context;
private String string;
public RestClient(Context context, String string)
{
this.context = context;
this.string = string;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(context, "Buscando seu Produto","Por favor, espere um momento...",true ,false);
//I've already tried:
/*ProgressDialog dialog = new ProgressDialog(context);
dialog.setTitle("Buscando seu Produto");
dialog.setMessage("Por favor, espere um momento...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);*/
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(URL... params) {
try {
//Some WebService gets and Json conversions using my string variable
//and some Thread.sleep that counts 2000 miliseconds to do all the queries
dialog.dismiss();
} catch (IOException | InterruptedException |JSONException e) {
e.printStackTrace();
dialog.dismiss();
return e.getMessage();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
And in my activity I call the class RestClient when I click a button like this:
--- EDIT : I forgot to mention that I have an AlertDialog in this same activity that CAN be shown sometimes before and after the ProgressDialog ---
private Button buttonConfirm;
private EditView evString;
private String theString;
private String returnFromExecute;
private RestClient restClient;
private AlertDialog.Builder dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_access_webservice);
evString = (EditText) findViewById(R.id.editViewMyString);
buttonConfirm = (Button) findViewById(R.id.buttonConfirm);
dialog = new ProgressDialog(IdentificacaoDeProdutoActivity.this);
dialog.setTitle("Error");
dialog.setMessage("Please try again");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
buttonConfirmar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
theString = evString.getText().toString();
if(!(theString!=null && theString.trim().length()>0)) //To check if theString is not null
{
dialog.show();
}
restClient = new RestClient(AccessWebserviceActivity.this, theString);
//Then I call execute and put a Thread.sleep a bit longer to compensate the ones I have in my doInBackground
restClient.execute();
try {
Thread.sleep(2050);
} catch (Exception e) {
dialog.show();
return;
}
}
}
}
The problem is that my ProgressDialog never shows. I've already tried getParent(), getApplication() and getApplicationContext() instead of AccessWebserviceActivity.this but none have worked. Someone Have any idea what is happening and what should I do?
you have not created progress dialog try this.
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog= new ProgressDialog(context);
dialog.setMessage("on Progress");
dialog.show();
super.onPreExecute();
}
returnFromExecute = restClient.get();
Remove that statement. You have already:
restClient.execute();
That should do.
The result of doInBackground() you should handle in onPostExecute(). It cannot be handled or retrieved in onCreate().
You need to call
dialog = ProgressDialog.show(context, "Buscando seu Produto","Por favor, espere um momento...",true ,false);
and remove
dialog.show();
Also put your dialog.dismiss(); method in onPostExecute(). This dialog.dismiss() method is good in catch block but what's its purpose if you are calling this method in try block. It will remove progress dialog as soon as you call this AsyncTask.
After a lot of researches about Threads and Process I found out that I had to encapsulate the all the code I have after my
RestClient.execute in a
new Thread(new Runnable() { public void run() { // My code } });
so that the execution of the code happened in background as well as the WebService query.
EDIT:
Even if creating a new Thread works, it is not recommended! The right thing to do would be to create another class that extends AsyncTask to do job.
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);
}
}
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.
I get this error "Can't create handler inside thread that has not called Looper.prepare()"
Can you tell me how to fix it?
public class PaymentActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.payment);
final Button buttonBank = (Button) findViewById(R.id.buttonBank);
buttonBank.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = ProgressDialog.show(PaymentActivity.this, "",
"Redirecting to payment gateway...", true, true);
new Thread() {
public void run() {
try {
startPayment("Bank");
} catch (Exception e) {
alertDialog.setMessage(e.getMessage());
handler.sendEmptyMessage(1);
progressDialog.cancel();
}
}
}.start();
}
});
StartPayment Method:
private void startPayment(String id) {
Bundle b = getIntent().getExtras();
final Sail sail = b.getParcelable(Constant.SAIL);
final Intent bankIntent = new Intent(this, BankActivity.class);
try {
Reservation reservation = RestService.createReservation(
sail.getId(),
getSharedPreferences(Constant.PREF_NAME_CONTACT, 0));
bankIntent.putExtra(Constant.RESERVATION, reservation);
// <workingWithDB> Storing Reservation info in Database
DBAdapter db = new DBAdapter(this);
db.open();
#SuppressWarnings("unused")
long rowid;
rowid = db.insertRow(sail.getId(), sail.getFrom(),
sail.getTo(), sail.getShip(), sail.getDateFrom().getTime(),
sail.getPrice().toString(), reservation.getId().floatValue());
db.close();
// </workingWithDB>
String html = PaymentService.getRedirectHTML(id, reservation);
bankIntent.putExtra(Constant.BANK, html);
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog alertDialog = builder.create();
alertDialog.setMessage(e.getMessage());
alertDialog.show();
}
startActivity(bankIntent);
}
You should know that when you try to modify your UI , the only thread who can do that is the UiThread.
So if you want to modify your UI in another thread, try to use the method: Activity.runOnUiThread(new Runnable);
Your code should be like this :
new Thread() {
public void run() {
YourActivity.this.runOnUiThread(new Runnable(){
#Override
public void run(){
try {
startPayment("Bank");//Edit,integrate this on the runOnUiThread
} catch (Exception e) {
alertDialog.setMessage(e.getMessage());
handler.sendEmptyMessage(1);
progressDialog.cancel();
}
});
}
}
}.start();
I assume you create a Handler in startPayment() method. You can't do that, as handlers can be created on th UI thread only. Just create it in your activity class.
Instead of new Thread() line, try giving
this.runOnUiThread(new Runnable() {
you cant change any UI in thread you can use runOnUIThread or AsyncTask for more detail about this click here
I've found that most thread handling can be replaced by AsyncTasks like this:
public class TestStuff extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonBank = (Button) findViewById(R.id.button);
buttonBank.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new StartPaymentAsyncTask(TestStuff.this).execute((Void []) null);
}
});
}
private class StartPaymentAsyncTask extends AsyncTask<Void, Void, String> {
private ProgressDialog dialog;
private final Context context;
public StartPaymentAsyncTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(context);
// setup your dialog here
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage(context.getString(R.string.doing_db_work));
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(Void... ignored) {
String returnMessage = null;
try {
startPayment("Bank");
} catch (Exception e) {
returnMessage = e.getMessage();
}
return returnMessage;
}
#Override
protected void onPostExecute(String message) {
dialog.dismiss();
if (message != null) {
// process the error (show alert etc)
Log.e("StartPaymentAsyncTask", String.format("I received an error: %s", message));
} else {
Log.i("StartPaymentAsyncTask", "No problems");
}
}
}
public void startPayment(String string) throws Exception {
SystemClock.sleep(2000); // pause for 2 seconds for dialog
Log.i("PaymentStuff", "I am pretending to do some work");
throw new Exception("Oh dear, database error");
}
}
I pass in the Application Context to the Async so it can create dialogs from it.
The advantage of doing it this way is you know exactly which methods are run in your UI and which are in a separate background thread. Your main UI thread isn't delayed, and the separation into small async tasks is quite nice.
The code assumes your startPayment() method does nothing with the UI, and if it does, move it into the onPostExecute of the AsyncTask so it's done in the UI thread.
Try
final Handler handlerTimer = new Handler(Looper.getMainLooper());
handlerTimer.postDelayed(new Runnable() {
public void run() {
......
}
}, time_interval});