ProgressDialog keeps on showing despite being cancelled and hidden - java

Right now I'm simulating the showing of a ProgressDialog for an event that is expected to take several seconds.
I'm doing it this way:
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage(getString(R.string.calendar_load));
progressDialog.setCancelable(false);
progressDialog.show();
Thread t=new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run() {
progressDialog.cancel();
progressDialog.hide();
But even though I've checked in debug that the progressDialog.cancel() and progressDialog.hide() execute the dialog just keeps on showing apparently in an indefinite way.
What could be causing such behavior?
PROBLEM SOLVED: Thanks to everyone who has answered/commented, it looks like an emulator bug (indeed it has also worked some times on emulator).

Call progressDialog.dismiss();

Could you try this snippet?
progressDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
while (progressDialog.getProgress() <= progressDialog.getMax()) {
Thread.sleep(100);
handle.sendMessage(handle.obtainMessage());
if (progressDialog.getProgress() == progressDialog.getMax()) {
progressDialog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
Handler handle = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDialog.incrementProgressBy(1);
}
};

Related

AsynchTask freezing while a postDelayed handler is running

I'm pretty new to app development, but I have an issue I can't figure out.
I have a splash screen I am using to load various things that the app needs to function (config files, html from the internet) and the latter is giving me a huge problem. Here is the code
Document doc = null;
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.splash);
//Fix loading data, dunno why this happens
try {
doc = new getHtml().get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Utils.saveData(Splash.this, doc);
Intent mainIntent = new Intent(Splash.this, PocketFrameNavigation.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
public static class getHtml extends AsyncTask<Void, Void, Document> {
protected Document doInBackground(Void... args) {
try {
return Jsoup.connect(DROP_DATA_URL).get();
} catch(Exception e) {
return null;
}
}
protected void onPostExecute(Document html){
doc = html;
}
}
The code that's giving me an issue is the inside the try statement. It seems to freeze the main thread, no matter where I put it. Is there something I am doing terribly wrong? Thanks in advance for the help.
Also, the getHTML function works whenever there is not a post delayed handler involved. so i think it has something to do with that.
I think that will be work:
Document doc = null;
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.splash);
new GetHTMLContent().excute();
}
private static class GetHTMLContent extends AsyncTask<Void, Void, Document> {
protected Document doInBackground(Void... args) {
try {
return Jsoup.connect(DROP_DATA_URL).get();
} catch(Exception e) {
return null;
}
}
protected void onPostExecute(Document html){
doc = html;
Utils.saveData(Splash.this, doc);
goToMainActivity();
}
}
private void goToMainActivity(){
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(Splash.this, PocketFrameNavigation.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
}

ProgressDialog - why runnable doesn't make appear ProgressDialog?

When I try to update text in my progressDialog like someone suggests here or here.
In my case, I'm trying to update the text in a loop while the progressDialog is not dismissed (?) elsewhere...
But my loop inside the runnable doesn't seems work, or better, the runnable doesn't make show the progressDialog.
So, in this way the code shows the progressDialog:
#Override
public void onDirectionFinderStart() {
String title = "PriscaLobby";
String msg = "Loading...";
progressDialog = ProgressDialog.show (MapsActivity.this,title,msg,true,false);
//--> runOnUiThread(changeMessage);
}
private Runnable changeMessage = new Runnable() {
#Override
public void run() {
progressDialog.setMessage("bruka");
while (progressDialog.isShowing()) {
try {
Thread.sleep(1500);
if (progressDialog.isShowing())
progressDialog.setMessage("Can you wait, please?");
Thread.sleep(1500);
if (progressDialog.isShowing())
progressDialog.setMessage("Here we are..");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
In this way NO:
#Override
public void onDirectionFinderStart() {
String title = "PriscaLobby";
String msg = getString(R.string.calculate_directions);
progressDialog = ProgressDialog.show (MapsActivity.this,title,msg,true,false);
runOnUiThread(changeMessage);
}
private Runnable changeMessage = new Runnable() {
#Override
public void run() {
progressDialog.setMessage("bruka");
while (progressDialog.isShowing()) {
try {
Thread.sleep(1500);
if (progressDialog.isShowing())
progressDialog.setMessage("Can you wait, please?");
Thread.sleep(1500);
if (progressDialog.isShowing())
progressDialog.setMessage("Here we are..");
} catch (InterruptedException e) {
e.printStackTrace();
}
} //Log.v(TAG, strCharacters);
}
};
Why?

Creating a slidshow in android

I am creating an application in which user can start slideshow (auto-play) of images by clicking a specific button. I have started a thread in which a new image is set to my imageView after a 1 sec. Problem is that my app stop responding and crashes after few seconds.
Please check my code and help me to resolve this issue. (variables are correctly initialized)
playThread = new Runnable() {
#Override
public void run() {
synchronized (this) {
for (int i=pos;i<mImageIds.length;i++){
//pos++;
selectedImage.setImageResource(mImageIds[i]);
try {
wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
}};
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
runOnUiThread(playThread);
}
});
}
my logcat while app freezes!
The runOnUiThread() method is meant to update the user interface. Any other logic shouldn't happen there. So I would suggest something like this:
Thread t = new Thread() {
for (int i=pos;i<mImageIds.length;i++){
runOnUiThread(new Runnable() {
#Override
public void run() {
selectedImage.setImageResource(mImageIds[i]);
}};);
try {
wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
t.start();
}
});
Please note, I didn't test this code.

Android Runnable Slowing down my device

I'm trying to develop an app which gets some data from an HTML webpage and displays it every second.
For that i'm using a runnable in this way:
In the OnCreate() method:
mHandler.removeCallbacks(mMuestraMensaje);
mHandler.postDelayed(mMuestraMensaje, 5000);
And then this other method:
private Runnable mMuestraMensaje = new Runnable() {
public void run() {
try {
returned = test.GetSensorData(newString);
rowTextView.setText(returned);
} catch (Exception e) {
e.printStackTrace();
}
mHandler.removeCallbacks(mMuestraMensaje);
mHandler.postDelayed(this, 500);
}
};
The problem is that if i press the back button, for example, the app starts to behave slowly and until i don't force close the whole app the device runs too slow!
Thank you!
EDIT
This is the whole class:
public class HttpExample extends Title {
GetMethodEx test, moredata ;
String returned;
TextView rowTextView, rowTextView2;
LinearLayout ll;
private Handler mHandler = new Handler();
String newString;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpexample);
rowTextView = (TextView)findViewById(R.id.textView2);
rowTextView2 = (TextView)findViewById(R.id.textView1);
mHandler.removeCallbacks(mMuestraMensaje);
mHandler.postDelayed(mMuestraMensaje, 5000);
Bundle extras = getIntent().getExtras();
newString = extras.getString("STRING_I_NEED");
test = new GetMethodEx();
moredata = new GetMethodEx();
try {
String name = moredata.GetName(newString);
rowTextView2.setText(name);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(mMuestraMensaje , 0, 500, TimeUnit.MILLISECONDS );
}
private Runnable mMuestraMensaje = new Runnable() {
public void run() {
try {
returned = test.GetSensorData(newString);
} catch (Exception e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable(){
rowTextView.setText(returned);
});
}
};
}
Your program slows down because you are running the thread on the GUI thread. That isn't recommended. However, I notice you are setting text after you are done. Here's a few things you could do.
Run the sensor data gathering in a different thread. Update the text by the runOnUiThread command.
Use an AsyncTask, this seems to be an ideal situation for one.
For such a regular occurrence, that doesn't require a UI thread, I would suggest using a ScheduledExecutorService.
The simplest to start with would be the first, but I would look carefully at the second option. The first option would be something like this: (Note, you will need to replace MainActivity with the name of your activity)
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(mMuestraMensaje , 0, 500, TimeUnit.MILLISECONDS );
private Runnable mMuestraMensaje = new Runnable() {
public void run() {
try {
returned = test.GetSensorData(newString);
} catch (Exception e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable(){
rowTextView.setText(returned);
});
}
};
You can attach you Handler to work on a different thread by using HandlerThread. For example:
HandlerThread ht = new HandlerThread("nonUiThread");
ht.start();
Handler mHandler = new Handler(ht.getLooper());
but more preferably, I would suggest you to use AsyncTask in your case.
Got it to work with this:
private Runnable mMuestraMensaje = new Runnable() {
public void run() {
try {
returned = test.GetSensorData(newString);
} catch (Exception e) {
e.printStackTrace();
}
HttpExample.this.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
rowTextView.setText(returned.get(0)+returned.get(1));
rowTextView2.setText(returned.get(2));
}
});
}
};

Run thread from another thread

I test the following code and the Toast message did not appear and the "TestMethod" did not call "Catch" method , please help me ?
public void TestMethod()
{
Test= new Thread(new Runnable() {
public void run() {
try{
Catch();
}
catch (Exception ioe)
{
}
}
});
Test.start();
}
public void Catch()
{
Test2= new Thread(new Runnable() {
public void run() {
try{
Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show();
}
catch (Exception ioe)
{
}
}
});
Test2.start();
}
May be runOnUiThread helpful to you.
runOnUiThread lets you ride on the UI thread and let s you to perform action on UI thread.
Try this:
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show();
}
});
You should call Toast.makeText on UI thread. Read this for more details.
You can make a toast only from the UI Thread. If you have access to the activity, you can change your code like thi
public void TestMethod()
{
Test= new Thread(new Runnable() {
public void run() {
try{
Catch();
}
catch (Exception ioe)
{
}
}
});
Test.start();
}
public void Catch()
{
activity.runOnUiThread(new Runnable() {
public void run() {
try{
Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show();
}
catch (Exception ioe)
{
}
}
});
}
This is the complete solution and it should work perfectly
Some methods will only run on the uithread, (runOnUiThread is a method on the activity, so if you can't reach it, than just put a variable
private final Activity activity = this;
and call the runOnUiThread from there
public void TestMethod() {
Test= new Thread(new Runnable() {
public void run() {
try{
Catch();
}
catch (Exception ioe) {
//always log your exceptions
Log.e("simpleclassname", ioe.getMessage(), ioe);
}
}
});
Test.start();
}
public void Catch() {
Test2= new Thread(new Runnable() {
public void run() {
try{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show();
});
catch (Exception ioe) {
//always log your exceptions
Log.e("simpleclassname", ioe.getMessage(), ioe);
}
}
});
Test2.start();
}
The thread you are using does not allows toast to show. You must do UI related stuff on a UI thread. If you are not on Main Thread, then you need to use runOnUiThread.

Categories