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();
Related
Activity from which I am calling AsyncTask for sign in.
If it returns true then, switch to another activity.
signIn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("On Click Sign In", "Before PD shown");
// pd.show();
Log.d("On Click Sign In", "After PD shown");
try {
if (new SignIn(SessionLogin.this).execute(email, pass).get())
{
Log.d("onClick", "True");
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
Intent i = new Intent(SessionLogin.this, DashBoardMain.class);
// pd.dismiss();
Log.d("SessionLogin", "true SignIn");
startActivity(i);
finish();
}
else
{
Toast.makeText(SessionLogin.this, "Sorry! Something went wrong. Please try again.", Toast.LENGTH_LONG).show();
Intent i = new Intent(SessionLogin.this, Woftos_sign_in_up.class);
// pd.dismiss();
Log.d("SessionLogin", "false || Null SignIn");
startActivity(i);
finish();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
AsyncTask in which I am connecting to database and returning values.
Till the asynctask runs, I wanna show ProgressDialog.
public class SignIn extends AsyncTask<String, Void, Boolean> {
String queryString;
ProgressDialog PD;
public static String NodeID=null;
public static String Gender=null;
public static String imageName=null;
String result;
Context context;
public SignIn(Context mcontext){
context=mcontext;
Log.d("constructor", "context "+context.toString());
PD=new ProgressDialog(mcontext);
PD.setProgressStyle(ProgressDialog.STYLE_SPINNER);
PD.setTitle("Please Wait...");
PD.setMessage("Signing in...");
PD.setCancelable(false);
PD.setIndeterminate(true);
PD.show();
}
protected void onPostExecute(Boolean x) {
super.onPostExecute(x);
if(PD.isShowing()){
Log.d("onPostExecute", "ProgressDialog b4 dismiss");
PD.dismiss();
Log.d("onPostExecute", "ProgressDialog after dismiss");
}
}
#Override
protected Boolean doInBackground(String... arg0) {
Log.d("in async", "" + arg0[0] + " " + arg0[1]);
try {
//Connecting to database
DBConnect.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
queryString = "{\"query\":\"START n=node(*) WHERE n.Email_Id='"
+ arg0[0] + "' AND n.Password='" + arg0[1]
+ "' RETURN n.Password,id(n),n.Gender,n.Profile_Photo\", \"params\":{}}";
try {
//Sending Query
DBConnect.sendQuery(queryString);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//Getting result of Query
result = DBConnect.readInputStream();
JSONObject obj1 = new JSONObject(result);
JSONArray nameArray = obj1.getJSONArray("data");
int res=nameArray.length();
if(res==0)
{
return false;
}
result = nameArray.getJSONArray(0).getString(0);
NodeID = nameArray.getJSONArray(0).getString(1);
Gender = nameArray.getJSONArray(0).getString(2);
//imageName = nameArray.getJSONArray(0).getString(3);
Log.d("NodeID-Gender in SignIn", ""+result+" " + NodeID+" "+Gender);
DashBoardMain.nodeID=NodeID;
DashBoardMain.DBGender=Gender;
//DashBoardMain.imageName=imageName;
return true;
//DashBoardMain.imageName=imageName;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
No matter what I do, ProgressDialog never shows up. Rest of the code works fine to connect with Database and returns the values.
Please help..
try like this in asynctask,
#Override
protected void onPreExecute() {
PD=new ProgressDialog(mcontext);
PD.setProgressStyle(ProgressDialog.STYLE_SPINNER);
PD.setTitle("Please Wait...");
PD.setMessage("Signing in...");
PD.setCancelable(false);
PD.setIndeterminate(true);
PD.show();
super.onPreExecute();
}
#Override
protected void onPostExecute(String[] result) {
PD.dismiss();
super.onPostExecute(result);
}
Override the OnPreExecute() of AsyncTask and paste
context=mcontext;
Log.d("constructor", "context "+context.toString());
PD=new ProgressDialog(mcontext);
PD.setProgressStyle(ProgressDialog.STYLE_SPINNER);
PD.setTitle("Please Wait...");
PD.setMessage("Signing in...");
PD.setCancelable(false);
PD.setIndeterminate(true);
PD.show();
show your ProgressDialog in onPreExecute() method and dismiss it in onPostExecute() method of AsyncTask.. like this.
protected void onPreExecute() {
PD=new ProgressDialog(mcontext);
PD.setProgressStyle(ProgressDialog.STYLE_SPINNER);
PD.setTitle("Please Wait...");
PD.setMessage("Signing in...");
PD.setCancelable(false);
PD.setIndeterminate(true);
PD.show();
};
and
protected void onPostExecute(Boolean x) {
super.onPostExecute(x);
if(PD.isShowing()){
Log.d("onPostExecute", "ProgressDialog b4 dismiss");
PD.dismiss();
Log.d("onPostExecute", "ProgressDialog after dismiss");
}
}
Try to use a pre excecute like this.
public SignIn(Context mcontext){
context=mcontext;
Log.d("constructor", "context "+context.toString());
}
protected void onPreExecute() {
super.onPreExecute();
PD=new ProgressDialog(context);
PD.setTitle("Please Wait...");
PD.setMessage("Signing in...");
PD.setCancelable(false);
PD.setIndeterminate(true);
PD.show();
}
OR--------------- it may because of your process is completed suddenly so progressdialog may closed suddenly.To avoid this in your post execute try :
protected void onPostExecute(Boolean x) {
super.onPostExecute(x);
if(PD.isShowing()){
Log.d("onPostExecute", "ProgressDialog b4 dismiss");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
PD.dismiss();
}}, 3000);
Log.d("onPostExecute", "ProgressDialog after dismiss");
}
}
OR------------------------
Remove the .get() from your aynctask call,get() waits if necessary for the computation to complete, and then retrieves its result. This means, that you are blocking your UI thread, waiting for the result.
Solution: Don't call get
Usually, you will call a function (callback) in the postExecute.
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();
}
My Question
How to show a progress bar in android while waiting to receive an SMS?
The dialog should fulfill the following conditions
The dialog should be dismissed in maximum for 5 minutes.
The dialog should be dismissed if SMS is received before 5 minutes.
What I tried
public class GetSMS extends Activity {
...
...
private boolean progressDialogFlag;
private ProgressDialog progressDialog;
...
...
new SMSReceiver().execute();
}
public class SMSReceiver extends AsyncTask<Void, Integer, Void> {
protected void onPreExecute() {
// start a progressdialog box
super.onPreExecute();
progressDialogFlag = true;
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Waiting to Receive SMS...");
progressDialog.setCancelable(false);
progressDialog.show();
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
if (progressDialogFlag == true) {
progressDialog.setProgress(progress[0]);
}
if (progress[0] == 100 || progressDialogFlag == false) {
progressDialog.dismiss();
}
}
protected void onPostExecute(Void result) {
}
#Override
protected Void doInBackground(Void... params) {
int interval = 2;
int totalDuration = 5 * 60 * 1000; // 5 min
int sleepPeriod = (totalDuration / 100) * interval;
for (int i = 2; i <= 100; i += 2) {
publishProgress(i);
try {
Thread.sleep(sleepPeriod);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
}
smsReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
progressdialog = false;
}
}
What are my doubts
I think the use of progressDialogFlag to dismiss the progressDialog when an Sms is received before 5 min is causing the problem.
The use of variable progressDialogFlag in UI and worker thread is causing some kind of race condition.
Thanks for help.
can try some thing like below when you start the progressDialog
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(null!=progressDialog && progressDialog.isShowing()){
// try{
progressDialog.dismiss();
}
}
}, 5*60*1000);
but need some more checks......
Do like this:
private ProgressDialog p;
private void sendSMS(){
p = new ProgressDialog(Context);
registerReceiver(broadcastReceiver, SMSINTENT);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
p.dismiss();
getActivity().unregisterReceiver(this);
}
};
Don't know if it is the best solution, but it works!
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);
I am trying to display a dialog in a non-Activity class. Basically, I detect an object in my app, I would like to display a dialog and then switch activities. I'm getting a "java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()" in my logcat.
Here is some of my code:
public ImageTargetsRenderer(Context context) {
this.context = context;
mDialog = new ProgressDialog(context);
}
public void onDrawFrame(GL10 gl) {
testFlag = 0;
// DO NOT RENDER IF THERE IS NO TRACKABLE
if (!mIsActive)
return;
// Call our native function to render content
// RENDER IF THERE IS A TRACKABLE
testFlag = renderFrame();
System.err.println("ImageTargetsRenderer reports: " + testFlag);
if(testFlag > 0 && frameCount > 5)
{
frameCount = 0;
System.err.println("Starting to switch activities.");
mDialog.setTitle("Please wait");
mDialog.setMessage("Please wait");
mDialog.show();
new Thread() {
public void run() {
try{
sleep(5000);
} catch (Exception e) { }
// Dismiss the Dialog
mDialog.dismiss();
}
}.start();
Intent myIntent = new Intent(context, FlashActivity.class);
myIntent.putExtra("com.qualcomm.QCARSamples.ImageTargets.flagTest", testFlag);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(myIntent);
testFlag = 0;
return;
}
frameCount++;
}
Your Dialog should be called from the UIthread so try to use this,
context.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mDialog.show();
}
});
Hope this works.
You do this
context.runOnUIThread( new Runnable() {
public void run() {
// show the Dialog
mDialog.setTitle("Please wait");
mDialog.setMessage("Please wait");
mDialog.show();
}
});
}
Thread.sleep(5000);
context.runOnUIThread( new Runnable() {
public void run() {
// Dismiss the Dialog
mDialog.dismiss();
}
});
This is the exception you will get if you are performing any UI operation on any thread or from any background task. Also context.runOnUiThread won't work.
Instead use:
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
mDialog.dismiss();
}
});
You can use the same for showing where activity is the object of activity.