Android: Accessing ui elements from thread - android

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);
}
});

Related

Android handler.postDelayed is stopping my mediaplayer to run a song smothly?

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);
}
}
};

schedule timer for dialog in android

I am in a situation where I need to display the Rate dialog based on the following flow
Open the app (First time )--> display dialog every 2 minutes
If rated --> display dialog next month
If clicked on later button --> display dialog next week.
String rate_value=myPref.getString("rate_value", "later");
Log.e("rate", String.valueOf(rate_value));
if (rate_value=="later") {
initCalendarNextWeek();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showRateDialog();
}
});
}
}, nextWeekDate);
}
else if (rate_value=="now") {
initCalendarNextMonth();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showRateDialog();
}
});
}
}, nextMonthDate);
}
else if (rate_value=="no_thanks") {
myTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showRateDialog();
}
});
}
}, 120000, 120000);
}
public void initCalendarNextMonth(){
cal=Calendar.getInstance();
cal_day=cal.get(Calendar.DATE);
cal_month=cal.get(Calendar.MONTH);
cal_year=cal.get(Calendar.YEAR);
nextMonthDate=new Date();
nextMonthDate.setDate(cal_day);
nextMonthDate.setMonth(cal_month+1);
nextMonthDate.setYear(cal_year);
}
public void initCalendarNextWeek(){
cal=Calendar.getInstance();
cal_day=cal.get(Calendar.DATE);
cal_month=cal.get(Calendar.MONTH);
cal_year=cal.get(Calendar.YEAR);
nextWeekDate=new Date();
nextWeekDate.setDate(cal_day+7);
nextWeekDate.setMonth(cal_month);
nextWeekDate.setYear(cal_year);
}
Ok, so maybe look at Calendar class. The set methods of Date are deprecated so instead of using
nextMonthDate = new Date()
rather maybe use
nextMonthDate = new Calendar();
because then you can use the methods stated in the Calendar documentation such as add instead of using the setDate or setMonth. I hope this helps.

How to stop running thread whenever I want and to start whenever I want

The below code is starting the thread only once, but I want to stop and start thread again by calling below method.
Thread th;
int t=45;
onstartbuttton()
{
th= new Thread(new callmymethod());
th.start();
}
onstopbutton()
{
}
public class callmymethod implements Runnable {
// TODO Auto-generated method stub
#SuppressWarnings("null")
#Override
public void run() {
// TODO Auto-generated method stub
while(t>-1){
try{
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
time_btn.setText(""+t);
if(t==0)
{
Toast.makeText(getApplicationContext(), "Thread over", Toast.LENGTH_SHORT).show();
}
}
});Thread.sleep(1000);
// Log.i("Thread", "In run"+t);
t=t-1;
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
Now I want to stop thread, so what I have to write in onstopbutton() method and how to start again by calling onstartbutton() method.
You need to add a flag to your thread indicating that it should stop running.
You can use an AtomicBoolean:
final AtomicBoolean flag = new AtomicBoolean();
onstartbuttton() {
th= new Thread(new callmymethod(flag));
flag.set(true);
th.start();
}
onstopbutton() {
flag.set(false); // indicate that the thread should stop
}
public class callmymethod implements Runnable {
public AtomicBoolean flag;
public callmymethod(AtomicBoolean flag) {
this.flag = flag;
}
#Override
public void run() {
int t = 45; // start back from 45
while(t>-1 && flag.get()){
// do as before
}
}
}

how to stop the timer in android

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

Android: Accessing UI Element from timer thread

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);
}
});

Categories

Resources