I tried this code (seen below) and it says "Cannot resolve symbol 'customHandler'", I am a beginner so I don't know yet how to fix this problem.
It would be awesome, if you could explain me how to fix it.
I am thankfull for every help :D
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//------------------
//------------------
android.os.Handler customHandler = new android.os.Handler();
customHandler.postDelayed(updateTimerThread, 0);
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
//write here whatever you want to repeat
customHandler.postDelayed(this, 1000);
}
};
I am trying to make a method run from the begining once every minute.
customHandler is a local variable in your method onCreate, so method run() cannot see it.
Make customHandler a member variable of your class to fix.
//Member variable
android.os.Handler customHandler;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Assign value
customHandler = new android.os.Handler();
customHandler.postDelayed(updateTimerThread, 0);
}
private Runnable updateTimerThread = new Runnable() {
public void run()
{
//USE the value
customHandler.postDelayed(this, 1000);
}
};
Your customHandler object is not visible from your updateTimerThread.
Try to change the visibility of this variable by moving it outside of your method.
Here is an exemple:
android.os.Handler customHandler;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//------------------
//------------------
customHandler = new android.os.Handler();
customHandler.postDelayed(updateTimerThread, 0);
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
//write here whatever you want to repeat
customHandler.postDelayed(this, 1000);
}
};
But using a Timer and a TimerTask may be a better solution than recursively calling postDelay on your handler.
It's makes cleaner code and it assure you that it will be runned at a specific frequency (for example every minutes) whereas your solution only allows to fix the delay between the end of a run and the beginning of the next one (if it take 30s to run and delay is 1 minute, it will run every 1.5mn)
// declare your timer
Timer basicTimer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//------------------
//------------------
// create a Timer
basicTimer = new Timer();
// create the periodic task, here it's an anonymous class
TimerTask updateTimerThread = new TimerTask() {
public void run() {
//write here whatever you want to repeat
// no need to call postDelayed
}
};
// schedule the task to run every minutes
basicTimer.scheduleAtFixedRate(updateTimerThread, 0, 60*1000); // 1minutes = 60000 ms
}
Related
Consider an application, it will count down from 60 to 0 at intervals of 1 second.
public class MainActivity extends AppCompatActivity {
int time;
TextView timeDisplay;
private Handler handler new Handler();
#Override
protected void onCreate(Bundle savedinstanceState) {
super.onCreate(savedinstanceState);
setContentView(R.layout.activity_main);
time = 60;
timeDisplay (TextView) findViewByid(R.id.timeDisplay);
handler.removeCallbacks(updateTimer);
handler.postDelayed(updateTimer, 1000);
}
private Runnable updateTimer = new Runnable(){
public void run(){
// somthing here
}
};
}
I try to implement a count down timer like this but I am very new to android studio and java and did not really know how to implement this. Hence any comment will be very useful. Thank you.
Did you tried CountDownTimer? You could read more information here
CountDownTimer
Can you tell me where is the problem on this line: timerText.setText(seconds);.
public class ShowTimer extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.timer_test_xml);
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
int seconds;
TextView timerText = (TextView) findViewById(R.id.TimerTestId);
#Override
public void run() {
seconds++;
timerText.setText(seconds);
}
}, 0, 1000);
}}
I think what you want to do is display seconds in the text view. However, the TextView.setText(int) function does not do this (Im not actually sure what it does). What you want to do is timerText.setText(""+seconds); to convert the parameter into a string and change the function call to a different overloaded function.
seconds is an int, whereas I think you want to be passing as character sequence, or a reference to one via a resource id, as per the documentation.
Though this doesn't answer the OP's original question, there are alternative (and - if you agree with the recommendations from the Android docs - better) ways to do this described in this thread.
As with Richard's suggestion, your other problem is updating the TextView on the non-UI thread, so consider using a Handler.
Example
public class ShowTimer extends Activity {
private Handler mHandler;
private TextView timerText = null;
private int seconds;
private Runnable timerRunnable = new Runnable() {
#Override
public void run() {
timerText.setText(String.valueOf(seconds++));
mHandler.postDelayed(timerRunnable, 1000);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timer_test_xml);
mHandler = new Handler();
timerText = (TextView) findViewById(R.id.TimerTestId);
timerRunnable.run();
}
}
I want to repeatedly call a method after every 5-seconds and whenever I wish to to stop the repeated call of the method I may stop or restart the repeated call of the method.
Here is some sample code that whats really I want to implement. Please help me in this respect I would be very thankful to you.
private int m_interval = 5000; // 5 seconds by default, can be changed later
private Handler m_handler;
#Override
protected void onCreate(Bundle bundle)
{
...
m_handler = new Handler();
}
Runnable m_statusChecker = new Runnable()
{
#Override
public void run() {
updateStatus(); //this function can change value of m_interval.
m_handler.postDelayed(m_statusChecker, m_interval);
}
};
public void startRepeatingTask()
{
m_statusChecker.run();
}
public void stopRepeatingTask()
{
m_handler.removeCallbacks(m_statusChecker);
}
Set repeated task using this:
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
and if you wanted to cancel the task simply call t.cancel() here t is your Timer object
and you can also check comment placed below your answer they have given brief information about that.
Use a Handler in the onCreate() method. Its postDelayed() method causes the Runnable to be added to the message queue and to be run after the specified amount of time elapses (that is 0 in given example). Then this will queue itself after fixed rate of time (1000 milliseconds in this example).
Refer this code :
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
android.os.Handler customHandler = new android.os.Handler();
customHandler.postDelayed(updateTimerThread, 0);
}
private Runnable updateTimerThread = new Runnable()
{
public void run()
{
//write here whaterver you want to repeat
customHandler.postDelayed(this, 1000);
}
};
use TimerTask to call after specific time interval
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(),1, TimeInterval);
and
class UpdateTimeTask extends TimerTask {
public void run()
{
// do stufff
}
}
Do it in Android's way with the help of Handler.
Declare a Handler which does not leak Memory
/**
* Instances of static inner classes do not hold an implicit
* reference to their outer class.
*/
private static class NonLeakyHandler extends Handler {
private final WeakReference<FlashActivity> mActivity;
public NonLeakyHandler(FlashActivity activity) {
mActivity = new WeakReference<FlashActivity>(activity);
}
#Override
public void handleMessage(Message msg) {
FlashActivity activity = mActivity.get();
if (activity != null) {
// ...
}
}
}
Declare a runnable which handle your task
private Runnable repeatativeTaskRunnable = new Runnable() {
public void run() {
new Handler(getMainLooper()).post(new Runnable() {
#Override
public void run() {
//DO YOUR THINGS
}
};
Initialize handler object in your Activity/Fragment
//Task Handler
private Handler taskHandler = new NonLeakyHandler(FlashActivity.this);
Repeat task after fix time interval
taskHandler.postDelayed(repeatativeTaskRunnable , DELAY_MILLIS);
Stop repetition
taskHandler .removeCallbacks(repeatativeTaskRunnable );
You have to put this code inside the activity you want to call every 5 seconds
final Runnable tarea = new Runnable() { public void run() {
hola_mundo();//the operation that you want to perform }};
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
timer.scheduleAtFixedRate(tarea, 5, 5, TimeUnit.SECONDS);
I am in a google map project and here is my code in oncreate:
mapView = (MapView)findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(false);
mapView.setStreetView(true);
mapController = mapView.getController();
mapController.setZoom(19);
getLastLocation();
drawCurrPositionOverlay();
drawMalls();
animateToCurrentLocation();
but now i want to call this DrawMalls(); method after some seconds and unless the user closes this application this method will be being called after that time? Is there any way to do this?
You can use Handler and Runnable combination to execute statements after a period of time.
You can delay a Runnable using postDelayed() method of Handler.
Runnable mRunnable;
Handler mHandler=new Handler();
mRunnable=new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
drawMalls();
//If you want to re call this method at a gap of x seconds then you can schedule handler again
mHandler.postDelayed(mRunnable,2*1000);
}
};
mHandler.postDelayed(mRunnable,10*1000);//Execute after 10 Seconds
If you want to cancel this then you have to use removeCallback() method of Handler like mHandler.removeCallbacks(mRunnable);
Or You can use Timer. You can refer an example here http://thedevelopersinfo.wordpress.com/2009/10/18/scheduling-a-timer-task-to-run-repeatedly/
You can follow the instructions for using a ScheduledExecutorService here I've had bugs before where timer's wouldn't be stopped and started properly on 2.1, the scheduling scheme described worked perfectly for me though.
There are two ways
1) using Handler
2)Using Timer
//using Timer//
public void OnCreate(Bundle SaveInstanceState())
{
------------
-----------------
PreferedTime pTime=new preferedTime();
Timer t=new Timer(false);
t.Schedule(pTime,2000);
}
class PreferedTime extends TimerTask
{
public void run()
{
drawMalls();
}
}
//method 2//
public void OnCreate(Bundle SaveInstanceState())
{
-----------------
-----------------
Handler handler=new handler(new Runnable()
{
public void run()
{
drawMalls();
}
},2000);
You could use a java.util.Timer's schedule() method to arrange future execution of drawMalls():
Timer t = new Timer();
t.schedule(
new TimerTask()
{
public void run()
{
System.out.println("hello\n");
}
},
2000); // Milliseconds: 2 * 1000
I am unsure if drawMalls() is a static or non-static method. If it is static then it is straightforward to call in the TimerTask.run() method. Otherwise, you will need to arrange for the class instance to which drawMalls() belongs is available to the run() method of TimerTask:
class DrawMallsTask extends TimerTask
{
public DrawMallsTask(YourClass a_build) { _instance = a_instance; }
public void run() { _instance.DrawMalls(); }
private YourClass _instance;
};
Timer t = new Timer();
t.schedule(new DrawMallsTask(this), 2000);
EDIT:
To repeatedly run the task after every two seconds you can use:
t.scheduleAtFixedRate(new DrawMallsTask(this), 2000, 2000);
MyCount counter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter= new MyCount(60000,1000);
counter.start();
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
counter= new MyCount(60000,1000);
}
#Override
public void onTick(long millisUntilFinished) {
s1=millisUntilFinished/1000;
if(s1%2==0)
{
drawMalls();
}
}
}
this one calls drawMalls() for every 2 seconds..u can change it as required..
If re-executing code is not bound to state of application, but only to time period, look at Timer class
http://developer.android.com/reference/java/util/Timer.html
Timer timer;
function myCallerFunction(){
timer = new Timer();
timer.schedule(seconds * 1000); //must be in milliseconds
}
private class MyTask extends TimerTask {
public void run() {
drawMalls();
}
}
I have the following code that responds to a button click, changes the view and then after 5 seconds switches the view back:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
Button test = (Button)findViewById(R.id.browseLocation);
test.setOnClickListener(testListener);
}
private TimerTask revert = new TimerTask(){
#Override
public void run() {
setContentView(R.layout.menu);
}
};
private OnClickListener testListener = new OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.test);
Timer tim = new Timer();
tim.schedule(revert, 5000);
}
};
However this code does not work. The run method of the timetask is hit but setContentView fails. I assume it has something to do with scope inside the timetask.
How can I achieve the desired result?
Try yourActivityName.this.setContentView(). Do you know if revert is being called at all (i.e. using Logging)?
Found on another post that setContentView cannot be called from a non-UI thread.
Can achieve the desired affect using runOnUiThread, but not recommended.