Error inside the class - android

I have created this class, but there is an error last part saying
"Syntax error on token "(", delete this token" on the "timers.schedule part"
public class refrend
{
Timer timers = new Timer();
final Handler handler = new Handler();
int initial = 1000;
int looper = 6000;
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
new activityIns().execute();
}
});
}
};
timers.schedule(task, initial, looper);
}
Thanks for your help :)

what you can do is to create a function
public class refrend {
Timer timers = new Timer();
final Handler handler = new Handler();
int initial = 1000;
int looper = 6000;
public void your_Function(){
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
// new activityIns().execute();
}
});
}
};
timers.schedule(task, initial, looper);
}
}
now you can call that function in you class by your_Functino();
and if you want to use that function out side of class create it object and call
it
refrend object=new refrend();
object.your_Function();

Related

Cannot resolve symbol 'post'

The following code is showing the error of cannot resolve symbol post even if import android.os.Handler; is used. And also invalid method declaration, return type is required for Runnable object.
TextView tv = (TextView) this.findViewById(R.id.txt);
String[] str = new String[] { "72", "71", "70",
"73", "75", "74", "69", "76", "77", "78" };
final Handler h = new Handler();
h.post(new Runnable() {
#Override
public void run() {
Random generator = new Random();
final int random = generator.nextInt(str.length);
tv.setText(str[random]);
h.postDelayed(this, 1000);
}
});
The import is correct, the problem seem to be inside the runnable. If you want to run a rask with delay the direct method is postDelay. Two arguments, a runnable and the delay.
h.postDelay(new Runnable..., 1000);
This is because you're calling the method post() outside of a method in a class.
For example, if your code inside an Activity class,
This is wrong:
public class MainActivity extends AppCompatActivity {
final Handler h = new Handler();
// This is outside a method. It's wrong.
h.post(new Runnable() {
#Override
public void run() {
Random generator = new Random();
final int random = generator.nextInt(str.length);
tv.setText(str[random]);
h.postDelayed(this, 1000);
}
});
...
#Override
protected void onCreate(Bundle savedInstanceState) {
}
}
This is right:
public class MainActivity extends AppCompatActivity {
private void generateRandom() {
final Handler h = new Handler();
h.post(new Runnable() {
#Override
public void run() {
Random generator = new Random();
final int random = generator.nextInt(str.length);
tv.setText(str[random]);
h.postDelayed(this, 1000);
}
});
}
...
#Override
protected void onCreate(Bundle savedInstanceState) {
}
}

Android studio update textview every 5 seconds

Hi my app needs a realtime data from database and I'm posting it on my TextView and I can't update the TextView as the database updates. I tried using Timer but its still the same.
Here is my code,
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
timer.schedule(timerTask, 0, 5000);
}
private void stopTimerTask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
final AcceptCars Cars = (AcceptCars) getIntent().getSerializableExtra("cars");
renterLat.setText(Cars.renterLat);
renterLng.setText(Cars.renterLng);
Log.d(TAG,renterLat.getText().toString());
Log.d(TAG,renterLng.getText().toString());
}
});
}
};
}
And here is where I get the Cars.renterLat and Cars.renterLng,
public class AcceptCars implements Serializable {
#SerializedName("renterLat")
public String renterLat;
#SerializedName("renterLng")
public String renterLng;
}
This is the logic you should be following. I used a Handler instead of a Timer. Inside the run method you need to call your webservice and get the updated value from the db. Use runOnUiThread to update the value to the UI from a Thread.
See the code below,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Handler taskHandler = new Handler();
taskHandler.postDelayed(myTask, 0);
}
private Runnable myTask = new Runnable(){
public void run() {
queryDb();
// repeat the task
taskHandler.postDelayed(this, 1000);
}
};
private void queryDb(){
new Thread(new Runnable() {
#Override
public void run() {
// call you webservice
String data = callWebservice();
// parse the data in to AcceptCars pojo class
AcceptCars Cars = parseData(data);
//update the UI
runOnUiThread(new Runnable() {
#Override
public void run() {
renterLat.setText(Cars.renterLat);
renterLng.setText(Cars.renterLng);
}
});
}
}).start();
}
You can even use countdown timer.
Here is the link https://developer.android.com/reference/android/os/CountDownTimer.html
TimerTasks are really hard to deal with IMO. You should use a Handler and call postDelayed to do something after a certain amount of time.
Alternatively, you can try out this timer class I wrote:
import android.os.Handler;
public class Timer {
private Handler handler;
private boolean paused;
private int interval;
private Runnable task = new Runnable () {
#Override
public void run() {
if (!paused) {
runnable.run ();
Timer.this.handler.postDelayed (this, interval);
}
}
};
private Runnable runnable;
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
}
public void startTimer () {
paused = false;
handler.postDelayed (task, interval);
}
public void stopTimer () {
paused = true;
}
public Timer (Runnable runnable, int interval, boolean started) {
handler = new Handler ();
this.runnable = runnable;
this.interval = interval;
if (started)
startTimer ();
}
}
It is really simple to use.
You can use it like this:
Timer timer = new Timer(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
final AcceptCars Cars = (AcceptCars) getIntent().getSerializableExtra("cars");
renterLat.setText(Cars.renterLat);
renterLng.setText(Cars.renterLng);
Log.d(TAG,renterLat.getText().toString());
Log.d(TAG,renterLng.getText().toString());
}
}
}
}, 5000, true);

android implements runnable not working?

this is a simple code to understand the runnable .I tried but not working . can you guys help me pls this is my code
public class Autostart extends activity implements Runnable {
#override
public void run (){
System.out.println ("message");
}
}
}
this not printing any statements
If you are using an Activity, you need to write your code inside Activity lifecycle methods. onCreate() is called when the Activity is created. So starting your Runnable here would be the correct way to do it.
#Override
public void onCreate(Bundle savedInstanceState) {
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
System.out.println ("message");
}
};
handler.postDelayed(r, 1000);
}
You have to create a Thread object and call start() using that object.
Thread t = new Thread(this);
t.start();
Or Just use Handler
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do Something here
}
}, 5000);
You can use below code to print a value after regular interval of time
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
Log.e("on print timee", your value);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); // will execute after 1 sec
}
Hope this will help you
I found a similar solution to Swayam (android implements runnable not working?), however another handler.postDelayed reference within run() was required;
public void onCreate(
...
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
Log.i(TAG, "message");
handler.postDelayed(this, 1000);
...
}
};
handler.postDelayed(r, 1000);
Try following code
Handler mainThreadhandler = new Handler(getMainLooper());
mainThreadhandler.post(new Runnable(){
public void run(){
// UI work
}
});
public class Autostart extends activity implements Runnable {
Thread = thread;
#override
public void onCreate() {
thread = new Thread(this);
thread.start();
}
#override
public void run (){
System.out.println ("message");
}
}

Android: Repeat a method and delay other method after x seconds using handle

I'm new to android and i have a problem
I used same code to repeat and delay method for two class. One class work fine but other not. I don't know why. This is my code
SpeedMeterFragment.java
public class SpeedMeterFragment extends Fragment {
....
public void speedMeterBefore() {
totalRxBytesBefore = TrafficStats.getTotalRxBytes();
Log.d("test", "Before: " + String.valueOf(totalRxBytesBefore));
}
public void speedMeterAfter() {
totalRxBytesAfter = TrafficStats.getTotalRxBytes();
Log.d("test", "After: " + String.valueOf(totalRxBytesAfter));
}
public void speedMeterDifference() {
totalRxBytesDifference = totalRxBytesAfter - totalRxBytesBefore;
tvTest.setText(String.valueOf(totalRxBytesDifference/1024) + " kb/s");
Log.d("test", "Difference: " + String.valueOf(totalRxBytesDifference));
}
public void speedMeter() {
handler = new Handler();
handler.post(runnable = new Runnable() {
#Override
public void run() {
speedMeterBefore();
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
speedMeterAfter();
speedMeterDifference();
}
}, 1000);
handler.postDelayed(this, 1000);
}
});
}
}
and SaveDataUseage.java
public class SaveDataUseage extends BroadcastReceiver {
...
public void onReceive(Context context, Intent intent) {
...
savePreference();
}
public void savePreference() {
...
measureDataMB();
}
public void measureDataMBBefore() {
dataMBBefore = TrafficStats.getTotalRxBytes() / 1048576;
}
public void measureDataMBAfter() {
dataMBAfter = TrafficStats.getTotalRxBytes() / 1048576;
}
public void measureDataMBDifference() {
dataMBDifference = dataMBAfter - dataMBBefore;
}
public void measureDataMB() {
handler = new Handler();
handler.post(runnable = new Runnable() {
#Override
public void run() {
measureDataMBBefore();
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
measureDataMBAfter();
measureDataMBDifference();
}
}, 1000);
handler.postDelayed(this, 1000);
}
});
}
}
SpeedMeterFragment work fine, but not SaveDataUseage
Anybody help me?
Sorry for my bad English :)
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
//Your method called here
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
this code will repeat method after every second
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
//Your method called here
MyMethod(isCalledFromHandeler);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
use boolean argument isCalledFromHandeler to recognition the caller of method.
and then use
if(isCalledFromHandeler){
// Do Not call the Child Method
} else{
// Call the Child Method
}
Although its eight month old question, I also faced the similar problem and in solution I extended Handler class to AdvanceHandler with the postRepeated method.
Sample Usage
AdvanceHandler handler = new AdvanceHandler();
handler.postRepeated(new Runnable() {
#Override
public void run() {
//Your repeated task
}
}, 5000) //After every 5 seconds

update data to server in the background android

How to update data to server ? I have used the code below but its not executing after 10 mins.
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(new Runnable(){
public void run() {
//update data to server
}
}, 0, 600, TimeUnit.SECONDS);
You must use your own Thread.
Here is solution using AsyncTask....
All code put in your Activity class.
public void toCallAsynchronous() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
MyAsyncTask task = new MyAsyncTask();
task.execute(txtSearchField.getText().toString());
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 2000); // execute in every 2 second
}
// AsyncTask Class
private class MyAsyncTask extends AsyncTask<String, Object, List<ModelObject>> {
#Override
protected List< ModelObject > doInBackground(String... params) {
// Call web service
return null;
}
#Override
protected void onPostExecute(List< ModelObject > result) {
super.onPostExecute(rezultat);
// Update UI
}
}
Try with this
private static final ScheduledExecutorService worker = Executors
.newSingleThreadScheduledExecutor();
worker.schedule(new Runnable(){
public void run() {
//update data to server
}, 600, TimeUnit.SECONDS);

Categories

Resources