I am using this Asnc class my application, but at times when i quit the application. It crashes. "window leaked error : at line progDialog.show();" - Guess the ProgressDialog is causing the issue as it is still referencing to the activity(context), but i cant use getApplicationContext(), if i use getApplicationContext(), then the ProgressDialog wont work. How can i fix this issue ?
protected void executeSLPWebserviceTask(double latitude, double longitude,
String progressStr) {
WebserviceTask task = new WebserviceTask(this, progressStr);
task.execute(latitude, longitude);
}
class WebserviceTask extends AsyncTask<Double, Void, Float> implements OnDismissListener{
Context context;
ProgressDialog progDialog;
String progressString;
public WebserviceTask(Context context, String progressStr) {
this.context = context;
this.progressString = progressStr;
initProgDialog();
}
void initProgDialog(){
if(!isCancelled()){
try {
progDialog = new ProgressDialog(context);
progDialog.setCanceledOnTouchOutside(false);
progDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.btn_cancel),new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
progDialog.dismiss();
}
});
progDialog.setMessage(progressString);
progDialog.setOnDismissListener(this);
progDialog.show();
} catch (Exception e) {
Log.e("Web&RemoteServiceActivity", "Failed to add window for web service task");
}
}
}
#Override
protected void onPreExecute() {
addTask(this);
super.onPreExecute();
}
protected Float doInBackground(Double... latLong) {
Float slpFloat = 0f;
if(!isCancelled()){
if(internetServiceBound)
{
try {
slpFloat = internetSLPService.getSLPFromInternet(latLong[0].floatValue(),latLong[1].floatValue());
} catch (RemoteException e) {
Log.e("Webservice task", "Failed to get slp - Remote exception");
this.cancel(true);
}
catch (NullPointerException e) {
Log.e("Webservice task", "Failed to get slp - Null pointer exception");
this.cancel(true);
}
}
}
return slpFloat;
}
protected void onPostExecute(Float slpFloat) {
if (!isCancelled()) {
if(slpFloat >= 300 && slpFloat<=1100){
//seaLevelPressure = slpFloat;
setReferenceSeaLevelPressure(slpFloat);
updateSeaLevelPressureFromWeb(slpFloat);
Toast toast = Toast.makeText(getApplicationContext(), getString(R.string.msg_slp_updated_from_internet) + " : " + slpFloat, Toast.LENGTH_LONG);
toast.show();
addToastJob(toast);
progDialog.dismiss();
//lastCalibratedTime = System.currentTimeMillis();
}else if(slpFloat==0){
//If SLP value returned is 0, notify slp fetch fail and cancel progress dialog
Toast toast = Toast.makeText(getApplicationContext(),getString(R.string.msg_slp_fetch_fail), Toast.LENGTH_SHORT);
toast.show();
addToastJob(toast);
progDialog.dismiss();
}else{
//Notify invalid SLP and cancel progress dialog
Toast toast = Toast.makeText(getApplicationContext(),getString(R.string.msg_internet_slp_invalid), Toast.LENGTH_SHORT);
toast.show();
addToastJob(toast);
progDialog.dismiss();
}
}
this.cancel(true);
}
public void onDismiss(DialogInterface dialog) {
this.cancel(true);
}
#Override
protected void onCancelled() {
if(progDialog != null){
if(progDialog.isShowing())
progDialog.dismiss();
}
super.onCancelled();
}
}
Create progressDialog by overriding onCreateDialog(int id) in your activity. In your task in onPreExecute() method use showDialog(PROGRESS_DIALOG_ID); and in onPostExecute() method use dismissDialog(PROGRESS_DIALOG_ID);
Related
I'm new on android and I want to show a progress bar whenever user do tap on sndbtn and while sending data to my API and when the app finish to sending the data the progress bar have to dismiss.
I'm not sure how to implement the progress with the code that I have. Please some help?
sndbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (networkInfo != null && networkInfo.isConnected()) {
Request data = helper.sndData(Integer.parseInt(id));
request = new Request(Activity.this, API.POST, data);
try {
String response = request.execute("url").get();
Response response = new Response(response);
if (responseListModel.isSuccess()) {
Toast.makeText(getApplication(), responseListModel.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Activity.this, NewActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplication(), responseListModel.getMessage(), Toast.LENGTH_SHORT).show();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplication(), "Internet Error.", Toast.LENGTH_SHORT).show();
}
}
});
I would suggest using AsyncTask and show dialog in onPreExecute and close dialog in onPostExecute.
/**
* Check holiday schedule
*/
class CheckHolidayNoteAsync(context: Activity) : AsyncTask<Void, Void, HolidayScheduleInfo>() {
override fun doInBackground(vararg params: Void?): HolidayScheduleInfo {
//do network stuff here
return HolidayScheduleInfo(result)
}
override fun onPostExecute(result: HolidayScheduleInfo) {
//close dialog
}
/**
* Runs on the UI thread before [.doInBackground].
*
* #see .onPostExecute
*
* #see .doInBackground
*/
override fun onPreExecute() {
//show progress dialog
}
}
Use this code :
public ProgressDialog dialog;
public void showDialog() {
if (dialog == null) {
dialog = new ProgressDialog(getContext());
}
dialog.setMessage("Searching");
dialog.show();
}
public void hideDialog(){
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
Use these methods in your code :
sndbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (networkInfo != null && networkInfo.isConnected()) {
showDialog();
Request data = helper.sndData(Integer.parseInt(id));
request = new Request(Activity.this, API.POST, data);
try {
new Thread(new Runnable() {
#Override
public void run() {
String response = request.execute("url").get();
Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
hideDialog();
Response response = new Response(response);
if (responseListModel.isSuccess()) {
Toast.makeText(getApplication(), responseListModel.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Activity.this, NewActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplication(), responseListModel.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplication(), "Internet Error.", Toast.LENGTH_SHORT).show();
}
}
});
In my App my I am using AlertDialog in Async. But it freezes at a point when data is saving in database. what can I do to keep it running? It runs perfectly for sometime but stops after certain time when database is accessed.
Here's my code:
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
return null;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
CheckInternetConnection internet = new CheckInternetConnection(
getApplicationContext());
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
return;
} else {
setUpdatedBarcodes();
}
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here after
data is saved in DB
}
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
DB operations should be done in the background thread. Put it in doInBackground() method too.
I modify your code. may it helps..
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
} else {
setUpdatedBarcodes();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
when saving data in database don't do it on main thread do it on background thread. try code
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// do your work
}
},0);
or
new Thread(new Runnable() {
public void run() {
// do your work here
}
}).start();
My activity keep show the dialog, It seem don't do the doInBackground. It keep should the "Loading" screen .
Here is my code :
private class MapTask extends AsyncTask<Void, Void, Void> {
protected ProgressDialog dialog;
protected Context context;
public MapTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.dialog = new ProgressDialog(context, 1);
this.dialog.setMessage("Loading");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
try {
String countryName=country.getTitle();
List<Address> address = new Geocoder(context).getFromLocationName(countryName, 1);
if (address == null) {
Log.e(null, "Not found");
} else {
Address loc = address.get(0);
Log.e(null, loc.getLatitude() + " " + loc.getLongitude());
LatLng pos = new LatLng(loc.getLatitude(), loc.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 6));
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (Exception e) {
Log.v("ASYNC", "ERROR : " + e);
e.printStackTrace();
}
return null;
}
}
Could somebody help me?
You are not calling dialog.dismiss() anywhere. You should do it in the onPostExecute of your AsyncTask:
#Override
protected void onPostExecute(Void... aVoid) {
dialog.dismiss();
}
In fact it is doing the doInBackground stuff, the problem is that you aren't dismissing the dialog in onPostExecute() method
Just add dialog.dismiss() in onPostExecute method.
i've an progress circle that is set inside an AsyncTask. It shows for about a second as the asynctask is executing, then disappears. once the task is completed if i press the back button the circle shows for a long time. why is this?
private class AsyncGetRota extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog= ProgressDialog.show(NfcscannerActivity.this,
"Connecting to Server"," retrieving rota...", true);
//do initialization of required objects objects here
};
#Override
protected Void doInBackground(String... params) {
try {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
cancel(true);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressDialog.dismiss();
};
}
[update]
getRota.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "onclicked getRota");
String[] params = new String[]{"36", "18-09-2012"};
AsyncGetRota agr = new AsyncGetRota();
agr.execute(params);
for(int i = 0; i < 60; i++){
if(agr.isCancelled() == true){
Log.e(TAG, "asyncTask is finished");
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}//end of for loop
Intent intent = new Intent(NfcscannerActivity.this,
GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", rotaArray);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}// end of onclick
});
...
new MyAsyncTask().execute(string);
...
}
class MyAsyncTask extends AsyncTask<String, Void, Whatever > {
...
#Override
protected Whatever doInBackground(String... params) {
Log.e(TAG, "inside doInBackground");
rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);
return rotaArray;
}
#Override
protected void onPostExecute(Whatever result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
Intent intent = new Intent(NfcscannerActivity.this, GetRota.class);
Bundle b = new Bundle();
b.putSerializable("rotaArray", result);
intent.putExtra("rotaArrayBundle", b);
startActivity(intent);
}
}
You should let the execution continue after you start the AsyncTask, and not block it using some loop or something..
try to implement it like this:
protected void onPreExecute() {
dialog = new ProgressDialog(activity);
dialog.setMessage("Processing...");
dialog.show();
}
protected void onPostExecute(Void result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
};
that's always works for me
Couple of problems here, you do not initialize ProgressDialog, initialize a constructor that initializes you ProgressDialog like this...
public AsyncGetRota(Activity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity);
}
Then in onPostExecute check if your ProgressDialog is null, like this
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(progressDialog != null)
progressDialog.dismiss();
}
I am fetching Image and Text for GridView from a webservice, so its takes some time to display the GridView. I want to show a ProgressDialog till Grid gets fully loaded. What I have done till now is as below:
public class PCGridMain extends Activity
{
WebService web = new WebService();
private GridView gridView;
ProgressDialog dialog;
Bitmap icon;
int i, total;
URL url= null;
List<GridItem> list;
#Override
public void onCreate(Bundle grid)
{
super.onCreate(grid);
dialog = ProgressDialog.show(PCGridMain.this, "Loading...", "Loading App, Please wait.", true);
DialogWork dWork = new DialogWork();
dWork.execute();
setContentView(R.layout.main);
gridView = (GridView)findViewById(R.id.gridView1);
web.WebService1();
total = web.totalService;
list = new ArrayList<GridItem>();
for(i=0; i<total; i++)
{
Log.v("Try Block", "See what we get:-");
try
{
Log.v("GridMain", "try url" + Integer.toString(i));
url = new URL(web.arr[i][2]);
}
catch (MalformedURLException e)
{
Log.v("GridMain", "catch MalformedURLException" + Integer.toString(i));
e.printStackTrace();
}
try
{
Log.v("GridMain", "try BitmapFactory" + Integer.toString(i));
icon = BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch (IOException e)
{
Log.v("GridMain", "catch IOException" + Integer.toString(i));
e.printStackTrace();
}
list.add(new GridItem(icon, web.arr[i][1])); // Adding Icon & LAbel
}
gridView.setAdapter(new GridAdapter(this, list));
gridView.setOnItemClickListener(Itemlistener);
}
private OnItemClickListener Itemlistener = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
ViewHolder holder = (ViewHolder)view.getTag();
if(holder == null)
{
return;
}
Toast.makeText(PCGridMain.this, holder.label.getText(), Toast.LENGTH_SHORT).show();
Log.v("GridMain", "Intent Creation");
Intent intent = new Intent(view.getContext(), ShowService.class); Log.v("GridMain", "Intent Created");
intent.putExtra("ServiceId", web.arr[position][0]); Log.v("GridMain", "ValueAdded Sid");
intent.putExtra("SName", holder.label.getText()); Log.v("GridMain", "ValueAdded SName");
startActivity(intent);
}
};
class DialogWork extends AsyncTask<URL, Integer, Long>
{
protected Long doInBackground(URL... params)
{
try
{
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress)
{
}
protected void onPostExecute(Long result)
{
try
{
//setContentView(R.layout.main);
//gridView.setAdapter(new GridAdapter(PCGridMain.this, list));
dialog.dismiss();
}
catch (Exception e)
{
e.printStackTrace();
dialog.dismiss();
}
}
}
Please tell me that what code has to be placed at what exact location, whenever I do some changes, it either shows no effect or App closes due to some issue.
Thanks,
Haps.
Try to put all rendering part from server in doInBackground() and set the adapter in onPostExecute() . And even start the progressdialog in onPreExecute() in and dismiss it on onPostExecute() but not in onCreate(). I think it will solve ur problem....
This should be your inner AsyncTask class, change parameters as you need.
private class yourTask extends AsyncTask<Void, Void, ArrayList> {
String message;
ProgressDialog dialog;
public refreshTask(String message) {
this.message = message;
this.dialog = new ProgressDialog(PCGridMain.this);
}
#Override
protected void onPreExecute() {
dialog.setMessage(message);
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected ArrayList doInBackground(String... params) {
// Some work
}
#Override
protected void onPostExecute(ArrayList result) {
if(dialog.isShowing())
dialog.dismiss();
}
}
So you may call this class like:
new yourTask('Dialog message').execute();
I hope it solves your issue.
Here I am giving the complete answer to my question, So that it may help others to make it done easily...
public class PCGridMain extends Activity
{
WebService web = new WebService();
private GridView gridView;
ProgressDialog dialog;
Bitmap icon;
int i, total;
URL url= null;
List<GridItem> list;
#Override
public void onCreate(Bundle grid)
{
super.onCreate(grid);
Log.v("GridMain", "setContent");
setContentView(R.layout.main);
gridView = (GridView)findViewById(R.id.gridView1);
DialogWork dWork = new DialogWork();
dWork.execute();
}
private void ForLoop()
{
for(i=0; i<total; i++)
{
Log.v("Try Block", "See what we get:-");
try
{
Log.v("GridMain", "try url" + Integer.toString(i));
url = new URL(web.arr[i][2]);
}
catch (MalformedURLException e)
{
Log.v("GridMain", "catch MalformedURLException" + Integer.toString(i));
e.printStackTrace();
}
try
{
Log.v("GridMain", "try BitmapFactory" + Integer.toString(i));
icon = BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch (IOException e)
{
Log.v("GridMain", "catch IOException" + Integer.toString(i));
e.printStackTrace();
}
list.add(new GridItem(icon, web.arr[i][1])); // Adding Icon & LAbel
}
}
private OnItemClickListener Itemlistener = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
ViewHolder holder = (ViewHolder)view.getTag();
if(holder == null)
{
return;
}
Toast.makeText(PCGridMain.this, holder.label.getText(), Toast.LENGTH_SHORT).show();
Log.v("GridMain", "Intent Creation");
Intent intent = new Intent(view.getContext(), ShowService.class); Log.v("GridMain", "Intent Created");
intent.putExtra("ServiceId", web.arr[position][0]); Log.v("GridMain", "ValueAdded Sid");
intent.putExtra("SName", holder.label.getText()); Log.v("GridMain", "ValueAdded SName");
startActivity(intent);
}
};
class DialogWork extends AsyncTask<URL, Integer, String>
{
protected void onPreExecute()
{
Log.v("GridMain", "PreExecute()");
dialog = ProgressDialog.show(PCGridMain.this, "Loading...", "Loading App, Please wait.", false, true);
}
protected Long doInBackground(URL... params)
{
String response = "";
try
{
Log.v("GridMain", "doInBackground");
response = web.WebService1();
total = web.totalService;
}
catch (InterruptedException e)
{
Log.v("GridMain", "InterruptedException");
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String result)
{
try
{
// Response is in RESULT_VAR
Log.v("GridMain", "onPostExecute");
list = new ArrayList<GridItem>();
ForLoop();
gridView.setAdapter(new GridAdapter(PCGridMain.this, list));
gridView.setOnItemClickListener(Itemlistener);
dialog.dismiss();
}
catch (Exception e)
{
Log.v("GridMain", "Exception e");
e.printStackTrace();
dialog.dismiss();
}
}
}
}
I have used it as according to my needs, its just for the help, the complete code might give problem to you. So just take it as a reference.
Thanks & Regards,
Haps.
try dialog with this code else code seems working
dialog= new ProgressDialog(this);
dialog.setMessage("Loading");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.show();