progress dialog circle only showing after task - android

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();
}

Related

Android AlertDialog freezes when saving data in database

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

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.

Run a progress dialog while an other process is running

I am trying to run a progress dialog while an other process is running, and I can't do it.
the process that I want run is this:
public void Onclick_editar (View view)
{
float porc;
String repre;
try{
porc = Float.parseFloat(edit_porcentaje.getText().toString());
repre = edit_representante.getText().toString();
try
{
Hilo hilo;
hilo = new Hilo(2, "UPDATE eleccion SET porcentaje="+porc+", delegados='"+repre+"' WHERE id="+idd );
hilo.start();
while(hilo.isAlive()){}
hilo = new Hilo(4, idd);
hilo.start();
while(hilo.isAlive()){}
Toast.makeText(this, "¡Actualizada con éxito!", Toast.LENGTH_SHORT).show();
}
catch(SQLException e)
{
Toast.makeText(this, "Error: Fallo en la base de datos", Toast.LENGTH_SHORT).show();
}
}catch(Exception e)
{
Toast.makeText(this, "Rellena todos los campos", Toast.LENGTH_SHORT).show();
}
}
this is launching when I click a button. thanks!
EDIT/////////////
well I solved the problem with this code!!
public void button(View v) {
new waiting().execute();
}
class waiting extends AsyncTask<String, Void, Boolean> {
ProgressDialog progressdialog;
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
}
protected void onPreExecute() {
super.onPreExecute();
// Shows Progress Bar Dialog and then call doInBackground method
progressdialog = new ProgressDialog(Tab_adminver_modificar_eleccion.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....");
progressdialog.setCancelable(false);
progressdialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
try {
Thread.sleep(5000);
} catch (Exception e) {
}
return null;
}
}
but I don't use a toast in a method doInBackground (FC)
Do you mean you are waiting for hilo to finish in this line : while(hilo.isAlive()){}?
Use AsyncTask instead, make use of its onPostExecute
you can try like this your process will run in background and progress dialog will be executing as well but when process will complete progress dialog will dismiss..
public class asynTask1 extends AsyncTask<String, Void, Boolean> {
public asynTask1 (MainActivity activiy) {
context = activiy;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressdialog = new ProgressDialog(Splash.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....");
progressdialog.setCancelable(false);
progressdialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
// do process
}
U can call it onclick or also can onCreate.. it better to make separate class for asyntask1 and write
new asynTask1(MainActivity.this).execute(); where you want to call it..
i hope it will helps ...
If your purpose is to show a ProgressDialog, then you can use this function for displaying a progress dialog-
public static void showProgressLoader(Context context, int duration)
{
final ProgressDialog dialog = ProgressDialog.show(context, "", "Loading...");
dialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
dialog.dismiss();
}
}, duration);
}
In this finction, pass the context and duration in milliseconds for which you want to show, after that duration it will get dissmissed by itself.
public void launchRingDialog(View view) {
final ProgressDialog ringProgressDialog = ProgressDialog.show(MainActivity.this, "Please wait ...", "Downloading Image ...", true);
ringProgressDialog.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
**// the MYSql consultation should be here?**
} catch (Exception e) {
}
ringProgressDialog.dismiss();
}
}).start();

ProgressDialog freezes in async task

I am reading lat/lon from file, creating polygon and adding it to the map in AsyncTask. Everything is working fine - except progressDialog allways freezes at start of the action and dismissed after action is completed.This is my code:
UPDATED CODE:
private class shpLoading extends AsyncTask<GoogleMap, List<LatLng>, String> {
private ProgressDialog dialog;
private String path;
private int loaded;
public void setPath(String p){
this.path = p;
}
#Override
protected String doInBackground(GoogleMap... params) {
final ShpReader shpRead = new ShpReader();
try {
shpRead.read(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidShapeFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.setMax(shpRead.daugiakampiai().size());
int i = 0;
for(List<LatLng> a: shpRead.polygons()){
function.arAntLinijos(a);
for(int h = 0; h < a.size()-1; h++){
LatLng point = function.midPoint(a.get(h), a.get(h+1));
a.add(h+1, point);
h++;
if(i > 3000){
message("You reached max count!");
break;
}
}
publishProgress(a);
i++;
}
return "Done";
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(Measuring.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage(getString(R.string.loading));
dialog.setCancelable(false);
dialog.setProgress(0);
dialog.show();
}
}
#Override
protected void onProgressUpdate(List<LatLng>... values) {
dialog.setProgress(loaded++);
Polygon daug = mMap.addPolygon(new PolygonOptions()
.addAll(values[0])
.strokeWidth(1)
.strokeColor(Color.RED)
.fillColor(0x3F00FF00));
plotai.add(new Polygons(db.getMaxFieldID()+1, daug));
daug = null;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
}
Because you should draw your polygons not in onProgressUpdate method, but in doInBackground method. In onProgressUpdate method you have to update progress in your ProgressDialog object (in your code ProgressDialog is showed, but not updated its progress at all).

progress dialog displays after task is finished in asynctask

Hi i want to display progressdialog until a command is executed through telnet.
so i use asynctask for that purpose.
private class AsyncAction extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
catch (Exception e)
{
// TODO: handle exception
}
finally
{
pd.dismiss();
}
// pd.dismiss();
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
And i call asynctask in oncreate() like below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
new AsyncAction().execute();
}catch (Exception e) {
e.printStackTrace();
}
}
The problem is that i could not see progressdialog until command executes.
please help me solve the issue.
Thanks in advance.
EDIT
The code to send and read command
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length()-1);
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (ch == lastChar)
{
if (sb.toString().endsWith(pattern))
{
if (sb.toString().contains("cdkk"))
{
disconnect();
break;
}
else
{
return sb.toString();
}
}
else
{
disconnect();
break;
}
}
else if(sb.toString().contains("Failed"))
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(TelSampActivity.this);
String error="Invalid username or password!";
alertbox.setMessage(error);
alertbox.setTitle("Error");
alertbox.show();
System.out.println("bad user name");
disconnect();
break;
}
ch = (char) in.read();
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
}
catch (Exception e) {
e.printStackTrace();
}
}
public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt + " ");
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
}
catch (Exception e) {
e.printStackTrace();
}
}
Currently you are trying to do Network operations from onPostExecute because this method called from UI Thread . change your code as to get work in proper way
private class AsyncAction extends AsyncTask<String, Void, String>
{
public static boolean status=false;
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
try
{
telnet.connect("XXX.XXX.XXX.XXX", 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream());
// Log the user on
readUntil("login:");
write("jk");
readUntil("password:");
write("kk");
// Advance to a prompt
readUntil(prompt + "");
write("ping -t localhost\n");
readUntil(">");
write("cdkk");
// make status true or false if command successfully executed
status=true;
}
catch (Exception e)
{
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(String result)
{
pd.dismiss();
// check status if true then show AlertDialog
if(status==true){
AlertDialog.Builder alertbox =
new AlertDialog.Builder(TelSampActivity.this);
String msg="work finished!";
alertbox.setMessage(msg);
alertbox.show();
}
else{
// your code here
}
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TelSampActivity.this);
pd.setMessage("loading...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
You need to show the progress bar in onPreExecute() do the work in doInBackground() and then hide the progress bar in onPostExecute(). onPreExecute() and onPostExecute() are both executed on the main thread, where as doInBackground is executed in the background.
You are doing your work on onPostExecute() method which should be inside doInBackground()
show your progress dialog inside onPreExecute() and dismiss inside onPostExecute().

Categories

Resources