public Button stb;
static int cnt=0;
public ArrayList<RadioButton> Butgrp1 = new ArrayList<RadioButton>();
Timer myt;
TimerTask t;
stb.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
myt.mschedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Entering run");
Handler h=new Handler();
h.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Butgrp1.get(cnt).setChecked(true);
cnt=cnt+1;
if(cnt>4)
cnt=0;
if(cnt>0)
// Butgrp1.get(cnt-1).setChecked(false);
System.out.println(cnt);
}
});
}
});
//rg.getChildAt(cnt).setPressed(true);
}
},1000,2000);
I need to access a group of radio buttons on the ui and set it as checked at regular intervals, but i keep getting different errors, i realized i must use a handler, but its still not working...can anyone please tell me where i am going wrong....am a newbie and am trying out stuff to understand the working better...please help...
You have to create the Handler in the UI Thread, i.e. in onCreate of your Activity.
Because you create it in the run method of a background thread, the handler will execute your code in that very same background thread.
You could also initialize your Handler directly:
public class MyActivity extends Activity{
private Handler handler = new Handler();
//more code
}
And then don't use runOnUIThread:
handler.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Butgrp1.get(cnt).setChecked(true);
cnt=cnt+1;
if(cnt>4)
cnt=0;
if(cnt>0)
// Butgrp1.get(cnt-1).setChecked(false);
System.out.println(cnt);
}
});
EDIT:
Ok try this cleaned up code. Because you did not post your full Activity this won't work out of the box:
public class TestActivity extends Activity {
private Button button;
static int cnt=0;
public ArrayList<RadioButton> buttonArray = new ArrayList<RadioButton>();
private Timer timer = new Timer();
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
timer.schedule(new MyTimerTask(), 1000,2000);
}
});
}
private void doButtonStuff(){
buttonArray.get(cnt).setChecked(true);
cnt=cnt+1;
if(cnt>4){
cnt=0;
}
if(cnt>0){
// Butgrp1.get(cnt-1).setChecked(false);
System.out.println(cnt);
}
}
private class MyTimerTask extends TimerTask{
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
doButtonStuff();
}
});
}
}
}
You can pass the Activity as a parameter to the method that runs the timertask, and then you can use Activity.runOnUiThread to execute your tasks in UI Thread. There are lots of post in stackoverflow site regarding the usage of runOnUiThread usage.
You don't need to call runOnUIThread inside the handler. By calling post on the Handler instance, the runnable you pass will be executed on the UI thread at some point in the future. Change your code to look like this and it should work:
Handler h=new Handler();
h.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Butgrp1.get(cnt).setChecked(true);
cnt=cnt+1;
if(cnt>4)
cnt=0;
if(cnt>0)
// Butgrp1.get(cnt-1).setChecked(false);
System.out.println(cnt);
}
});
Related
hi i am new to Android programming i need little help in building a media player app in which i am using a seek bar to update the progress as below:
Handler handler = new Handler();
paly.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s_player.start();
p_bar.run();
}
});
Runnable p_bar = new Runnable() {
#Override
public void run() {
start_time = s_player.getCurrentPosition();
s_bar.setProgress((int) start_time);
handler.postDelayed(p_bar, 100);
}
};
so this code is updating sekkbar after 100ms, but the song is not playing smoothly???
I've spotted a mistake here, it might be related to the problem, might not.
Runnable p_bar = new Runnable() {
#Override
public void run() {
start_time = s_player.getCurrentPosition();
s_bar.setProgress((int) start_time);
handler.postDelayed(p_bar, 100);
}
};
in the p_bar you are calling the postDelayed within the run() method, while postDelay() will add the runnable object to the MessageQueue, and the run() method of the Runnable will be called by the System when this Runnable Object is reached in the Queue.
So it is like a loop, you can run, and postDelay will call run(), and run() will call postDelay() ....
So please don't call postDelay() in the run method.
Here is how i am doing;
paly.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s_player.start();
handler.postDelayed(p_bar,100);
}
});
Runnable p_bar = new Runnable() {
#Override
public void run() {
s_bar.setProgress((int) s_player.getCurrentPosition());
}
};
now the problem is its playing smothly but not updating progress bar
You have to implement seekbar listener....and this works for me
SeekBar.OnSeekBarChangeListener seekBarOnSeekChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
};
This is my code following,I am changing some iamges dynamically in my image view.
public class LoadingScreen extends Activity{
public static Integer[] imageList={R.drawable.food_pics1,R.drawable.food_pics2,R.drawable.food_pics3,
R.drawable.food_pics4,R.drawable.food_pics5,R.drawable.food_pics6,R.drawable.food_pics7,
R.drawable.food_pics8,R.drawable.food_pics9};
Thread thread;
ImageView foodImageView;
final Handler myHandler=new Handler();
public int currentImageIndex=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.load_xml);
foodImageView=(ImageView)findViewById(R.id.imageView_food);
// final int i=0;
final Runnable runnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
animateImages();
}
};
final int delay=500;
final long period=1000;
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
myHandler.post(runnable);
}
}, delay, period);
}
private void animateImages() {
// TODO Auto-generated method stub
foodImageView.setImageResource(imageList[currentImageIndex%imageList.length]);
currentImageIndex++;
foodImageView.getAnimation();
}
I want to stop the timer and finish this activity after 20 secs.how can I do that.
Try using this,
View v = new View(this);
v.postDelayed(new Runnable(){
public void run() {
// TODO Auto-generated method stub
//cancel your animation and finish the Activity here.
finish();
}
}, (long) 20000.0);
You can say something like this :
timer.cancel();
timer = null;
Save the TimerTask instance in the class and invoke cancel on it.
Here's a tip I found very useful without using Java's Timer: Try synchronizing things in the UI thread, especially if you want to do UI tasks. Example:
... onCreate() {
getUiThreadHandler().post(new Runnable(){
if (canceled()) {
return;
}
// Actual work
...
// Invoke again after delay
getUiThreadHandler().postDelayed(this, 500);
});
Good luck
I have been struggling to get a thread to launch and run in the background of my app.
My question is, How do I create a thread and launch it from a button? I'm sorry for creating this question but I have spent at least 5 hours with no progress at all.
your_button_id.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startThread();
}
});
create method
public void startThread()
{
Thread backgroundthread =new Thread( new Runnable()
{
public void run()
{
//Write your code that should be run on thread.Dont render UI here.
//render UI after thread in response handler like this...
responceHandler.sendEmptyMessage(0);
}});backgroundthread.start();
}
private Handler responceHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if(msg.what==0)
{
//Handle your UI here
}
}};
public Button stb;
static int cnt=0;
public ArrayList<RadioButton> Butgrp1 = new ArrayList<RadioButton>();
Timer myt;
TimerTask t;
stb.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
myt.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Entering run");
Handler h=new Handler();
h.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Butgrp1.get(cnt).setChecked(true);
cnt=cnt+1;
if(cnt>4)
cnt=0;
if(cnt>0)
// Butgrp1.get(cnt-1).setChecked(false);
System.out.println(cnt);
}
});
}
});
//rg.getChildAt(cnt).setPressed(true);
}
},1000,2000);
I need to access a group of radio buttons on the ui and set it as checked at regular intervals, but i keep getting different errors, i realized i must use a handler, but its still not working...can anyone please tell me where i am going wrong....am a newbie and am trying out stuff to understand the working better...please help...
You can try to use your own Handler instead of Timer and timed taks.
RefreshHandler mHandler = new RefreshHandler();
With:
class RefreshHandler extends Handler
{
#Override
public void handleMessage(Message msg)
{
postYourElements();
}
public void sleep(long delayMillis)
{
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
}
And than use the function:
private void postYourElements()
{
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Butgrp1.get(cnt).setChecked(true);
cnt=cnt+1;
if(cnt>4)
cnt=0;
if(cnt>0)
// Butgrp1.get(cnt-1).setChecked(false);
System.out.println(cnt);
}
});
mHandler.sleep(TimerIntervallInMs);
}
To start the Handler just call the postYourElements() function under onClick Method.
I'm not sure if this works for you but you can try.
youractivityname.this.runOnUiThread(new Runnable() {
public void run() {
Butgrp1.get(cnt).setChecked(true);
cnt=cnt+1;
if(cnt>4)
cnt=0;
if(cnt>0)
// Butgrp1.get(cnt-1).setChecked(false);
System.out.println(cnt);
}
});
This is my Service class:
public class MySrv extends Service {
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
final Context c = getApplicationContext();
Timer t = new Timer("mytimer");
TimerTask task = new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(c, "Not a beautyfull day today...", Toast.LENGTH_SHORT).show();
}
};
t.schedule(task, 5000, 6000);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
The application crashes at Toast.makeText()... So what am I doing wrong?
The TimerTask's run() method doesn't execute in the UI thread, so you can't do UI-related things like creating a Toast.
Investigate using a Handler or runOnUiThread() instead.
Example:
final Handler handler = new Handler ();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post (new Runnable (){
#Override
public void run() {
Toast.makeText(c, "Not a beautyfull day today...", Toast.LENGTH_SHORT).show();
}
});
}
The problem here is that you are trying to update the UI in the timers thread, you should use a Handler for this.
Read How to display toast inside timer?
You cannot make a Toast in another Thread, you can use a Handler to do it or use the runOnUiThread.
public class YourActivity extends Activity {
private Handler toastTeller;
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
toastTeller = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 2)
Toast.makeText(LibraryActivity.this, msg.obj.toString(),
Toast.LENGTH_LONG).show();
super.handleMessage(msg);
}
};
new Thread(new Runnable(){
public void run(){
Message msg = new Message();
msg.what = 2;
msg.obj = "Your item was downloaded.";
toastTeller.sendMessage(msg);
}
}).start();
}