Could someone tell me why my code is not working? I want to display a ProgressDialog, but the problem with the code below is that it does not appear, even when it has spent a lot of time processing the function ConsultaComercio. I have seen a lot of examples but I don't understand what I am doing wrong. I appreciate your help. Thanks in advance.
pd = ProgressDialog.show(this, "", "Loading...", true);
Toast.makeText(getApplicationContext(), "Cargando.... " + String.valueOf(numero_prueba), Toast.LENGTH_SHORT).show();
new Thread() {
public void run() {
try{
// Do some Fake-Work
ConsultaComercio();
numero_prueba=60000;
} catch (Exception e) { }
// Dismiss the Dialog
pd.dismiss();
}
}.start();
in your onCreate() do this,
Handler handler=new Handler()
{
public void handleMessage(Message msg)
{
if(pd.isShowing())
{
pd.dismiss();
}
};
and change your thread like this,
Toast.makeText(getApplicationContext(), "Cargando.... " + String.valueOf(numero_prueba), Toast.LENGTH_SHORT).show();
new Thread() {
public void run() {
try{
// Do some Fake-Work
ConsultaComercio();
numero_prueba=60000;
} catch (Exception e) { }
// Dismiss the Dialog
handler.sendEmptyMessage(0);
}
}.start();
You can't update the UI from just any thread. It must be an AsyncTask.
Related
I'm learning android and I don't know why this code doesn't work. Can you tell me why it doesn't work and take me correct code?
final ProgressDialog dialog = ProgressDialog.show(LoginScreen.this, "", "Loading. Please wait...", true);
Thread loggingStatus = new Thread() {
public void run() {
try
{
sleep(2000);
dialog.setMessage("Logging in. Please wait.");
sleep(2000);
dialog.dismiss();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
};
loggingStatus.start();
You have to move the portion of the background task that updates the ui onto the main thread. There is a simple piece of code for this:
putting runOnUiThread( new Runnable(){ .. inside run():
final ProgressDialog dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
Thread loggingStatus = new Thread() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
sleep(2000);
dialog.setMessage("Logging in. Please wait.");
sleep(2000);
dialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
};
loggingStatus.start();
You should not set the Text of ProgressDialog in background thread . All UI updation should be done only on UI thread(Main thread)
Either use AsyncTask or Handler for this logic or functionality
i am trying to display a Toast on the screen and when Toast fades off then move to the next question. I have tried with Thread but cannot seem to manage.
My code:
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getUserSelection()){
position = position + 3;
if (position < questionsArray.size()) {
curName = questionsArray.get(position).getName();
curArray = questionsArray.get(position).getAnswers();
curIscorrect = questionsArray.get(position).getIscorrect();
setupQuestionView(curName, curArray, curIscorrect);
} else {
StringGenerator.showToast(QuestionsActivity.this, "Your score : " + score + "/" + (questionsArray.size() / 3));
}
}else {
StringGenerator.showToast(QuestionsActivity.this, getString(R.string.noanswerselected));
}
}
});
and the getUserSelectionMethod:
private boolean getUserSelection() {
correct = (RadioButton)findViewById(group.getCheckedRadioButtonId());
if (correct == null){
return false;
}else {
correctAnswerText = correct.getText().toString();
if (map.get(correctAnswerText).equals(Constants.CORRECTANSWER)) {
score++;
setCorrectMessage();
return true;
} else {
setWrongMessage();
return true;
}
}
}
private void setCorrectMessage() {
correctToast = new Toast(QuestionsActivity.this);
correctToastView = getLayoutInflater().inflate(R.layout.correct, (ViewGroup) findViewById(R.id.correctRootLayout));
correctText = (TextView)correctToastView.findViewById(R.id.correctTextView);
correctText.setText(getString(R.string.correctAnswer));
correctToast.setDuration(Toast.LENGTH_SHORT);
correctToast.setView(correctToastView);
correctToast.show();
correctThread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
correctToast.cancel();
}
});
correctThread.start();
}
private void setWrongMessage() {
wrongToast = new Toast(QuestionsActivity.this);
wrongToastView = getLayoutInflater().inflate(R.layout.wrong, (ViewGroup) findViewById(R.id.wrongRootLayout));
wrongText = (TextView)wrongToastView.findViewById(R.id.wrongTextView);
wrongText.setText(getString(R.string.wrongAnswer));
wrongToast.setDuration(Toast.LENGTH_SHORT);
wrongToast.setView(wrongToastView);
wrongToast.show();
wrongThread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
wrongToast.cancel();
}
});
wrongThread.start();
}
Any suggestion on how to do this?
You can determine the toast visibility:
toast.getView().getWindowToken()
If the result is null, than your toast isn't visible anymore, and than you can run any code you want.
as stated in this answer you can start a thread that waits the duration of the Toast:
Thread thread = new Thread(){
#Override
public void run() {
try {
Thread.sleep(3500); // 3.5seconds!
// Do the stuff you want to be done after the Toast disappeared
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Toast.LENGTH_SHORT and Toast.LENGTH_LONG are only flags so you have to either hard code the duration or keep them in a constant. The durations are 3.5s (long) and 2s (short).
If you want to manipulate some of your views, you cannot do this in another thread than the "main" UI thread. So you have to implement a kind of callback/polling mechanism to get notified when the SleepThread has finished.
Check this answer to read about a couple of ways to do this. Probably the easiest of them to understand and implement is this:
After you started your Thread you can check if it is still alive and running by calling thread.isAlive(). In this way you can do a while loop that runs while the thread is running:
// start your thread
while(thread.isAlive()){}
// continue the work. The other thread has finished.
Please note that this is NOT the most elegant way to do this! Check the other possibilities in the answer I've mentioned above for more elegant solutions (especially the last one with the listeners is very interesting and worth reading!)
That's because the Thread class is purely executed in the background and you need to manipulate the view in the Main thread. To solve your issue just replace the Thread with AsynTask.
AsyncTask<Void,Void,Void> a = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
correctToast.cancel();
}
};
a.execute();
If you look at my code you can see my onPostExecute, this method is called in the Main Thread.
My Error was because i was trying to acess UI Elements through another Thread so modifying the code like this:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
QuestionsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
moveToNextQuestion();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
did the trick. I hope my answer helps someone!!!
Im Adding Progress Dialog in some Activity .But im getting Exception mention in title.how to resolve it.
dialog = ProgressDialog.show(Notification.this, "loading please wait",
"Loading. Please wait...", true);
new Thread() {
public void run() {
try{
performBackgroundProcess1();
//sleep(3000,000);
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
// dismiss the progress dialog
dialog.dismiss();
}
}.start();
Any thing wrong with this.all Background process is performed in performbackgroundprocess method.
You cant call dialog.dismiss(); in the background thread.
You can make Threads send messages to handlers when they are done and in the handler you can dismiss the dialog. Handlers work in ui thread
There is a tutorial about it
use runOnUiThread as:
new Thread() {
public void run() {
try{
performBackgroundProcess1();
//sleep(3000,000);
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
// dismiss the progress dialog
CurrentActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
}
}.start();
Here is my code segment I am trying to dismiss dialog but it is not getting dismissed and also i don't get any error on logcat.Please correct me where i am wrong ?
All the Log.v statement get executed.Even log.v statement after pd.dismiss() (Log.v("TAG","progress dismiss");) gets printed.
Please point my mistake or suggest some alternative way to dismiss the progressdialog.
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//do something
} else {
Log.v("TAG","above progressDialog");
final ProgressDialog pd = new ProgressDialog(ChangePassword.this);
ProgressDialog.show(ChangePassword.this, "", "Loading...", false, true);
new Thread() {
public void run() {
try {
sleep(2000);
Log.v("TAG","in try block");
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
// dismiss the progress dialog
pd.dismiss();
// Log.v("TAG","progress dismiss");
}
}.start();
Log.v("TAG","after start");
public void run()
{
try{
if (!(txtOldPass.getText().toString())
.equals(SetGetValues.getPassword())) {
Toast.makeText(ChangePassword.this,
"Invalid Old Password", Toast.LENGTH_SHORT)
.show();
txtOldPass.setText("");
txtNewPass.setText("");
txtCnfPass.setText("");
} else {
if (!(txtNewPass.getText().toString())
.equals(txtCnfPass.getText().toString())) {
Toast.makeText(ChangePassword.this,
"Re-Enter New Password",
Toast.LENGTH_SHORT).show();
txtOldPass.setText("");
txtNewPass.setText("");
txtCnfPass.setText("");
} else {
try {
handler = new Handler();
handler.postDelayed(new Thread (new Runnable(){
JSONStringer loginuser = new JSONStringer()
.object()
.key("userid")
.value(SetGetValues.getUserid()
.trim())
.key("password")
.value(txtCnfPass.getText()
.toString().trim())
.key("oldpassword")
.value(txtOldPass.getText()
.toString().trim())
.endObject();
StringEntity entity = new StringEntity(
loginuser.toString());
JSONObject results = bc
.returnJSONObject(loginuser,
"url");
String message = results
.getString("message");
String isvalid = results
.getString("isvalid");
if (isvalid.contains("FALSE")) {
} else {
//pd.dismiss();
Toast.makeText(
ChangePassword.this,
"Password changed successfully",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
//TODO: handle exception
e.printStackTrace();
}
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}), 1000);
}
}
});
You are not dismissing the same ProgressDialog that you are showing. Replace this:
final ProgressDialog pd = new ProgressDialog(ChangePassword.this);
ProgressDialog.show(ChangePassword.this, "", "Loading...", false, true);
with this:
final ProgressDialog pd = ProgressDialog.show(ChangePassword.this, "", "Loading...", false, true);
if (pd.isShowing()) {
pd.dismiss();
}
Instead of using thread Use Async Task
usage
You problem probably is, that you're trying to modify the UI (dismiss the dialog) from another thread. I'm surprised that you don't get an error message. Try dismissing the dialog from the UI thread, for example by using .runOnUIThread().
Because you are trying to use element of UI Thread progressDialog in a non UI thread .
This will be allowed through AsyncTask , handler or RunOnUIThread(runnable) only .
read more about them and use any one .
I want to open a ProgressDialog when I click on the List Item that opens the data of the clicked Item form the Web Service.
The ProgressDialog needs to be appeared till the WebContent of the clicked Item gets opened.
I know the code of using the Progress Dialog but I don't know how to dismiss it particularly.
I have heard that Handler is to be used for dismissing the Progress Dialog but I didn't found any worth example for using the Handler ultimately.
Can anybody please tell me how can I use the Handler to dismiss the Progress Dialog?
Thanks,
david
Hi this is what you want
public void onClick(View v)
{
mDialog = new ProgressDialog(Home.this);
mDialog.setMessage("Please wait...");
mDialog.setCancelable(false);
mDialog.show();
new Thread(new Runnable()
{
#Override
public void run()
{
statusInquiry();
}
}).start();
}
here is the web webservice that is called
void statusInquiry()
{
try
{
//calling webservice
// after then of whole web part you will send handler a msg
mHandler.sendEmptyMessage(10);
}
catch (Exception e)
{
mHandler.sendEmptyMessage(1);
}
}
and here goes handler code
Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case 10:
mDialog.dismiss();
break;
}
}
}
};
A solutiion could be this:
ProgressDialog progressDialog = null;
// ...
progressDialog = ProgressDialog.show(this, "Please wait...", true);
new Thread() {
public void run() {
try{
// Grab your data
} catch (Exception e) { }
// When grabbing data is finish: Dismiss your Dialog
progressDialog.dismiss();
}
}.start();