Why my TOAST is showing twice in post handler? - java

I want to show my toast message only once if the progressStatus reaches 100. Why is it that it is executed twice? Thank you for your kind responses.
new Thread(new Runnable() {
#Override
public void run() {
while (progressStatus < 100) {
// Update the progress status
progressStatus += 1;
// Try to sleep the thread for 50 milliseconds
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable(){
#Override
public void run() {
pb = dialog.findViewById(R.id.no_connectiondProgressBar);
pb.setProgress(progressStatus);
if (progressStatus == 100) {
final Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
View custom_view = getLayoutInflater().inflate(R.layout.custom_toast, null);
toast.setView(custom_view);
toast.show();
dialog.dismiss();
}
}
});
}
}
})

Move handler.post() to outside the while loop
new Thread(new Runnable() {
#Override
public void run() {
while (progressStatus < 100) {
// Update the progress status
progressStatus += 1;
// Try to sleep the thread for 50 milliseconds
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
handler.post(new Runnable(){
#Override
public void run() {
pb = dialog.findViewById(R.id.no_connectiondProgressBar);
pb.setProgress(progressStatus);
if (progressStatus == 100) {
final Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
View custom_view = getLayoutInflater().inflate(R.layout.custom_toast, null);
toast.setView(custom_view);
toast.show();
dialog.dismiss();
}
}
});
}
})

Related

How can I stop thread and properly display text by Toast in thread?

I need solution to stop my thread and display Toast.
Why doesn't stop my thread?
Why doesn't my solution display "success" by Toast?
This is my class StopperThread where I try stop by blinker my thread.
public class StopperThread implements Runnable{
private Context context;
private volatile boolean blinker;
public StopperThread(Context context){
this.context = context;
this.blinker = true;
}
#Override
public void run ()
{
Looper.prepare();
try {
while(blinker) {
Log.e("LOG","ACTIVE");
Thread.sleep(1000);
Toast.makeText(context, "success", Toast.LENGTH_SHORT).show();
}
} catch (InterruptedException e) {
e.printStackTrace();
blinker = false;
}
Looper.loop();
}
public void mystop() {
blinker = false;
}
}
This is my method clickedButton inside the Activity where I created thread.
private void clickedButton() {
final StopperThread stopperThread = new StopperThread(this);
Thread t1 = new Thread(stopperThread);
if(click)
{
t1.start();
click = false;
}
else
{
try {
stopperThread.mystop();
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
click = true;
}
}
I tried to change
/*First Try*/
final StopperThread stopperThread = new StopperThread(getApplicationContext());
/*Second Try*/
runOnUiThread(new Runnable() {
#Override
public void run() {
t1 = new Thread(stopperThread);
}
});

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?

Why when clicking the button on the second time it's not loop over the array from the start?

I have this button click method that I call it from onCreate:
public void addListenerOnButton()
{
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
byte[] response = null;
#Override
public void onClick(View arg0)
{
text = (TextView) findViewById(R.id.textView2);
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
for (int i = 0; i < ipaddresses.length; i++)
{
try
{
response = Get(ipaddresses[i]);
if (response == null)
{
text.post(new Runnable()
{
#Override
public void run()
{
counter++;
text.setText("Connection Failed: " + ipaddresses[counter]);
}
});
}
}
catch (Exception e)
{
String err = e.toString();
}
if (response!=null)
{
try
{
final String a = new String(response, "UTF-8");
text.post(new Runnable()
{
#Override
public void run()
{
text.setText(a);
}
});
iptouse = ipaddresses[i].substring(0, 26);
connectedtoipsuccess = true;
Logger.getLogger("MainActivity(inside thread)").info(a);
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
Logger.getLogger("MainActivity(inside thread)").info("encoding exception");
}
Logger.getLogger("MainActivity(inside thread)").info("test1");
break;
}
else
{
}
}
counter = 0;
}
});
t.start();
}
});
}
For the testing I did that the string array ipaddresses will contain two items of ips that not exist on my server in fact my server is also not working at all and that's only for the test.
When I click the button first time it's making a loop over the array and in both cases it return that response is null.
But then when it finish I click again on the button this time I see that it's doing once response = Get(ipaddresses[i]); and i = 0 and response is null but then instead getting inside the if (response == null) it's first doing the line response = Get(ipaddresses[i]); again now i == 1 only then it's entering the if (response == null) and then inside I see that now the variable counter = 2.
Then my program crash. I guess it's crashing since counter = 2 and the array size is also 2. But after the loop I did counter = 0; so why on the second time I click the button counter = 2?
Second why on the second time I click the button it's not getting inside to the if (response == null) when i == 0?
Try this:
private int counter = 0;
public void addListenerOnButton()
{
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
byte[] response = null;
#Override
public void onClick(View arg0)
{
text = (TextView) findViewById(R.id.textView2);
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
for (int i = 0; i < ipaddresses.length; i++)
counter = i;
{
try
{
response = Get(ipaddresses[counter]);
if (response == null)
{
text.post(new Runnable()
{
#Override
public void run()
{
counter++;
text.setText("Connection Failed: " + ipaddresses[counter]);
}
});
}
}
catch (Exception e)
{
String err = e.toString();
}
if (response!=null)
{
try
{
final String a = new String(response, "UTF-8");
text.post(new Runnable()
{
#Override
public void run()
{
text.setText(a);
}
});
iptouse = ipaddresses[i].substring(0, 26);
connectedtoipsuccess = true;
Logger.getLogger("MainActivity(inside thread)").info(a);
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
Logger.getLogger("MainActivity(inside thread)").info("encoding exception");
}
Logger.getLogger("MainActivity(inside thread)").info("test1");
break;
}
else
{
}
}
counter = 0;
}
});
t.start();
}
});
}

trying to stop execution for 2 seconds

I have a button and when clicked calls a method which starts a thread. but there is stop for that thread, fine. I want that to complete the thread first then to execute the rest of the code.
I tried to use wait() but not working.
public void configure(Button arg0,TextView arg1) throws InterruptedException{
//calling OpenDeviceListener
readText=arg1;
button= arg0;
//handler
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.d("Handler","running");
if (actualNumBytes != 0x00) {
Log.d("handler","if");
readText.append(String.copyValueOf(readBuffer, 0,
actualNumBytes));
Log.d("handler","if 312");
actualNumBytes = 0;
Log.d("handler","if end");
}
Log.d("handler","closed");
}
};
Log.d("163","tab");
uartInterface = new CH34xAndroidDriver(
(UsbManager) getSystemService(Context.USB_SERVICE), this,
ACTION_USB_PERMISSION);
Log.d("167","tab");
act_string = getIntent().getAction();
if(-1 != act_string.indexOf("android.intent.action.MAIN"))
{
Log.d(TAG, "android.intent.action.MAIN 171");
}
else if(-1 != act_string.indexOf("android.hardware.usb.action.USB_DEVICE_ATTACHED"))
{
Log.d(TAG, "android.hardware.usb.action.USB_DEVICE_ATTACHED 175");
}
if(!uartInterface.UsbFeatureSupported())
{
Toast.makeText(this, "No Support USB host API", Toast.LENGTH_SHORT).show();
Log.d("182","tab");
readText.setText("No Support USB host API");
Log.d("184","tab");
uartInterface = null;
}
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if(READ_ENABLE == false) {
READ_ENABLE = true;
Log.d("192","tab");
handlerThread = new readThread(handler);
handlerThread.start();
}
Log.d("192","End");
try{
this.wait(100);
}
catch(InterruptedException e){
e.printStackTrace();
Log.d("Exception",e.getMessage());
}
// TODO Auto-generated method stub
Log.d("205","OpenDeviceListener");
boolean flags;
if(false == isConfiged) {
Log.d("209","OpenDeviceListener");
Toast.makeText(global_context,""+((Boolean)uartInterface.isConnected()), Toast.LENGTH_LONG).show();
isConfiged = true;
// writeButton.setEnabled(true);
if(uartInterface.isConnected()) {
Toast.makeText(global_context,""+(Boolean)uartInterface.isConnected(), Toast.LENGTH_SHORT).show();
Log.d("213","OpenDeviceListener");
flags = uartInterface.UartInit();
if(!flags) {
Log.d(TAG, "Init Uart Error 2");
Toast.makeText(global_context, "Init Uart Error", Toast.LENGTH_SHORT).show();
} else {
if(uartInterface.SetConfig(baudRate, dataBit, stopBit, parity, flowControl)) {
Log.d(TAG, "Configed");
}
}
}
}
}
and plz clear one thing the stop() is not called for the thread, up to when the thread will run.
Thanks
final Runnable runnable = new Runnable() {
#Override
public void run() {
//this method will be called after 2 seconds
//do your task here
}
};
final Handler h = new Handler();
h.removeCallbacks(runnable); // cancel the running action (the
// hiding process)
h.postDelayed(runnable, 2000);
try this:
Object lock = new Object;
synchronized(lock){
lock.wait();
}
this will block current Thread running these code.
when it's time notify the blocked code
synchronized (lock) {
lock.notify();
}
if just want to sleep the thread for a specific time why not use
Thread.sleep(1000);

object not locked by thread before notify()

Iam making app for listening .mp3 words in greek language so i have mediaplayer and after lets say 1000ms it should display next word depends on .mp3 file so i have 3 functions play, pause and stop.. I need to pause thread and then continue when it ends. In my thread is not working pause method by calling notify i simply dont know how to lock object before calling notify().. Here is my Code i would be rly glad for every help..
class MyinnerThread implements Runnable {
String name;
Thread tr;
boolean suspendFlag;
int i = 0;
MyinnerThread(String threadname) {
name = threadname;
tr = new Thread(this, name);
suspendFlag = false;
tr.start();
}
public void run() {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(i == 0){tv1.setText("trhead1");}
if(i == 1){tv2.setText("trhead2");}
if(i == 2){tv3.setText("trhead3");}
if(i == 3){tv4.setText("trhead4");}
if(i == 4){tv5.setText("trhead5");}
if(i == 5){tv6.setText("trhead6");}
if(i == 6){tv7.setText("trhead7");}
if(i == 7){tv8.setText("trhead8");}
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(this) {
while(suspendFlag) {
try {
tr.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
i++;
}
});
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
}
void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() {
suspendFlag = false;
tr.notify();
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.play:
if(mp.isPlaying()){
mp.pause();
play.setBackgroundResource(R.drawable.play);
t.mysuspend();
Toast.makeText(getApplicationContext(), "Pause", Toast.LENGTH_SHORT).show();
}
else if(!mp.isPlaying()){
mp.start();
if(runningThread){
t.myresume();
}
if(!runningThread){
runningThread = true;
t = new MyinnerThread("name");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(), "Play", Toast.LENGTH_SHORT).show();
play.setBackgroundResource(R.drawable.pause);
}
break;
case R.id.stop:
Toast.makeText(getApplicationContext(), "Stop", Toast.LENGTH_SHORT).show();
mp.release();
Thread.currentThread().interrupt();
t = null;
runningThread = false;
setPlayer();
play.setBackgroundResource(R.drawable.play);
break;
}
}

Categories