By starting a new activity, it starts again and again - android

I set a textview, which I use for timer-function.
When the timer reachs my wanted time it should start a new activity, that set my Layout to another one.
textfield=(TextView)findViewById(R.id.TVTimer);
handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
while (Running){
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
// TODO: handle exception
}
handler.post(new Runnable() {
#Override
public void run(){
number+=1;
textfield.setText(String.valueOf(number));
if (number>5) {
Intent intent = new Intent(getApplicationContext(), Uebung2.class);
startActivity(intent);
}
}
} );
}
}
};
new Thread(runnable).start();
That is the called class:
public class Uebung2 extends Oberklasse {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//Liegestützen1(2);
setContentView(R.layout.new);
}
}
Now I am having the problem after the timer reached the time, which I want, my app is settin g the layout again and again for every second.
What is the solution to set the layout for once?

beacuse you have place this
handler.post(new Runnable() {
#Override
public void run(){
number+=1;
textfield.setText(String.valueOf(number));
if (number>5) {
Intent intent = new Intent(getApplicationContext(), Uebung2.class);
startActivity(intent);
}
}
} );
inside your while loop.
also check your "number" value.
try your while loop as
int i=1000;
while (i<5000){
try {
Thread.sleep(i);
i+=1000;
}
catch (InterruptedException e) {
e.printStackTrace();
// TODO: handle exception
}
}
and after this execute your runnable.

use this
textfield=(TextView)findViewById(R.id.TVTimer);
boolean loop = true;
handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
while (loop){
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
// TODO: handle exception
}
handler.post(new Runnable() {
#Override
public void run(){
number+=1;
textfield.setText(String.valueOf(number));
if (number>5) {
loop = false; // this will end loop
Intent intent = new Intent(getApplicationContext(), Uebung2.class);
startActivity(intent);
}
}
} );
}
}
};
new Thread(runnable).start();

Related

How to Update UI while a task is running in another thread in android?

I have tried updating my user interface using the text view what i have done is a run a while loop indefinitely and left the thread for sleep for one second..
int i;
while(true)
{
Thread.Sleep(1000);
textView.setText(updateTime);
}
Use runOnUiThread and surround with try catch for Thread.sleep(1000)
int i;
while(true)
{
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
textView.setText(updateTime);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Try this one arnab...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.displayid);
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
bundle = msg.getData();
textView.setText(bundle.getString("mKey"));
}
};
}
public void press(View v) {
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
synchronized (this) {
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bundle = new Bundle();
message = handler.obtainMessage();
simpleDateFormat = new SimpleDateFormat("hh:mm:ss YYYY/mm/dd", Locale.US);
date = simpleDateFormat.format(new Date());
bundle.putString("mKey", date);
message.setData(bundle);
handler.sendMessage(message);
}
}
}
}).start();
}
Try runOnUiThread:
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(updateTime);
}
});

Stop runnable on button click

I have Runnable and have two Handlers for button background color change after some music is played.
Now how can I stop the music played using runnable for a ever delay of 700 mili sec on a button click named stop.
handler=new Handler();
runnable = new Runnable() {
#Override
public void run() {
for (int i = 0; i<Uirkeys1.length; i++) {
final int value = i;
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
copyView.get(cnt1).getBackground().setAlpha(100);
ModeSound(Integer.parseInt(CopyMultimap.get(copykey[cnt1]).get(3)));
}
});
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run()
copyView.get(cnt1).getBackground().setAlpha(500);
cnt1++;
}
});
}
}
};
new Thread(runnable).start();
cnt1=0;
}
});
}
You could create a class MyRunnable that implements Runnable, and create a field in it
private boolean stopped = false;
public void stop() { stopped = true; }
And then you should check in your execution loop
if(!stopped) {..do work..} else return .
And you can of course call the stop() method on your MyRunnable object.

Wake up waiting thread on touch event from activity?

I have this thread wating for onTouchEvent()
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),"Your session expired Please Login again",Toast.LENGTH_SHORT).show();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
final Logout l=new Logout();
l.setContext(Ac2.this);// passing context of Ac3.java to Logout.java
l.execute(sessid,uname);
}
});
}
};
what i want is notify this waiting thread when user touches a mobile screen..
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"Your session expired Please Login again",
Toast.LENGTH_SHORT).show();
try {
synchronized (disconnectCallback) {
disconnectCallback.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
final Logout l = new Logout();
l.setContext(Ac2.this);// passing context of Ac3.java to
// Logout.java
l.execute(sessid, uname);
}
});
}
};
and in onTouch event call:
disconnectCallback.notifyAll();
Try this
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"Your session expired Please Login again",
Toast.LENGTH_SHORT).show();
}
});
try {
synchronized(disconnectCallback){
disconnectCallback.wait();
final Logout l=new Logout();
l.setContext(Ac2.this);// passing context of Ac3.java to Logout.java
l.execute(sessid,uname);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Inside onTouch
synchronized (disconnectCallback) {
disconnectCallback.notify();
}

timer.setText("setTextHere") does not work inside the thread

timer.setText("setTextHere") does not work inside the thread.
Thread thread1 = new Thread(){
TextView timer;
int t;
public void run(){
timer=(TextView) findViewById(R.id.timer);
try{
timer.setText("setTextHere");
sleep(5000);
}
catch(Exception e){
e.printStackTrace();
}
finally{
Intent new1 = new Intent("com.example.app1.MENU");
startActivity(new1);
}
}
};
thread1.start();
_t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
_count++;
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
_tv.setText( "" + _count );
}
});
}
}, 1000, 1000 );
You cannot touch UI from background thread. Try to use AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
On your onCreate() add:
h = new Handler();
add this somewhere:
class SetText implements Runnable {
public void run() {
// do UI task
timer.setText("setTextHere");
}
}
on someFunction() modify like this:
...
try
{
h.post( new SetText() );
sleep(5000);
}
...
final TextView timer = (TextView) findViewById(R.id.timer);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
timer.post(new Runnable() {
public void run() {
timer.setText("setTextHere");
}
});
} catch (Exception e) {
e.printStackTrace();
} finally {
Intent new1 = new Intent("com.example.app1.MENU");
startActivity(new1);
}
}
}).start();
you could use this and initialize the setText before initializing the Thread
Thread thread1 = new Thread(){
int t;
public void run(){
try{
sleep(5000);
}
catch(Exception e){
e.printStackTrace();
}
finally{
Intent new1 = new Intent("com.example.app1.MENU");
startActivity(new1);
}
}
};
TextView timer;
timer=(TextView) findViewById(R.id.timer);
timer.setText("setTextHere");
thread1.start();

CalledFromWrongThreadException

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ThraedDemo objDemo = new ThraedDemo();
Thread objThread = new Thread() {
#Override
public void run() {
objDemo.firstMethod();
}
};
objThread.start();
}
class ThraedDemo {
private void firstMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);
Thread.sleep(10000);
Log.v("Thread","1111111111111111sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
secondMethod();
}
private void secondMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
((ImageView)findViewById(R.id.ImageViewResult)).setImageResource(nums[n+1]);
n++;
Thread.sleep(10000);
Log.v("Thread","22222222222 sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
firstMethod();
}
};
objThread.start();
}
};
objThread.start();
}
}
I use the above code but it is not running.it got CalledFromWrongThreadException what is the problem inb the above code.Please give me some suggestions.Thanks in advance
I think you can't do view modifications from another thread than the UI thread, so either create handlers in the oncreate and post your thread to it, or use AsyncTask, or runOnUIThread method to send portions of code directly to the UI thread.
I edited your 2nd function code, I see your code is loop forever cause the firstMethod call secondMethod and the secondMethod call the new firstMethod to start and then loop forever. I removed it and moved the code update ImageView into the UI Thread, could you try this:
class ThraedDemo {
private void firstMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
runOnUiThread(new Runnable() {
public void run(){
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);
}
});
Thread.sleep(10000);
Log.v("Thread","1111111111111111sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
secondMethod();
}
};
objThread.start();
}
private void secondMethod() {
Thread objThread2 = new Thread() {
#Override
public void run() {
try {
runOnUiThread(new Runnable() {
public void run(){
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n+1]);
}
});
n++;
Thread.sleep(10000);
Log.v("Thread","22222222222 sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
}
};
objThread2.start();
}
}

Categories

Resources