Skip to content

Instantly share code, notes, and snippets.

@methodin
Created June 11, 2013 18:14
Show Gist options
  • Save methodin/5759313 to your computer and use it in GitHub Desktop.
Save methodin/5759313 to your computer and use it in GitHub Desktop.
Setting up local timers in fragments/activities
public class DummyFragment extends Fragment {
private UpdateHandler handler;
private Timer timer;
@Override
public void onCreate(Bundle savedInstanceState) {
handler = new UpdateHandler(this);
super.onCreate(savedInstanceState);
}
@Override
public void onResume() {
Calendar c = Calendar.getInstance(Locale.getDefault());
timer = new Timer("MyTimer", true);
timer.scheduleAtFixedRate(new UpdateTask(), 1000 - c.get(Calendar.MILLISECOND), 1000);
super.onResume();
}
@Override
public void onPause() {
timer.cancel();
timer.purge();
super.onPause();
}
private class UpdateTask extends TimerTask {
private From from;
private final Bundle bundle = new Bundle();
private List<TestEntity> items;
private long[] ids;
public void run() {
if (from == null) {
from = new Select().from(TestEntity.class).where("Date IS NOT NULL");
}
items = from.execute();
if (items.size() > 0) {
if(ids == null || ids.length != items.size()) {
ids = new long[items.size()];
}
for (int i = 0; i < items.size(); i++) {
ids[i] = items.get(i).getId();
}
bundle.clear();
bundle.putLongArray("ids", ids);
Message msg = handler.obtainMessage(0);
msg.setData(bundle);
handler.sendMessage(msg);
}
}
}
private static class UpdateHandler extends Handler {
final private WeakReference<DummySectionFragment> reference;
public UpdateHandler(DummySectionFragment parent) {
this.reference = new WeakReference<DummySectionFragment>(parent);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
DummySectionFragment fragment = reference.get();
if(fragment != null) {
Bundle bundle = msg.getData();
long[] ids = bundle.getLongArray("ids");
for (int c = 0; c < ids.length; c++) {
int start = fragment.listView.getFirstVisiblePosition();
for (int i = start, j = fragment.listView.getLastVisiblePosition(); i <= j; i++)
if (ids[c] == ((TestEntity) fragment.listView.getItemAtPosition(i)).getId()) {
View view = fragment.listView.getChildAt(i - start);
((TestListAdapter) fragment.listView.getAdapter()).getView(i, view, fragment.listView);
break;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment