I am new to android. I'm creating an contest app in which I have a ListView
which contains status of the event. Whether it is started or not. It should be updated automatically when the current time exceeds the event start time.
I'm using a AsyncTask
but it is not very accurate.
@Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater scheduleInflater = LayoutInflater.from(getContext());
final Holder h;
if(view == null){
view = scheduleInflater.inflate(R.layout.custom_list , parent , false);
h = new Holder();
h.eventName=(TextView) view.findViewById(R.id.eventNameCustomList);
h.eventStatus=(TextView) view.findViewById(R.id.eventStatus);
h.leftTime = (TextView) view.findViewById(R.id.leftTime);
h.rightTime= (TextView) view.findViewById(R.id.rightTime);
view.setTag(h);
}else{
h = (Holder) view.getTag();
}
final data d = getItem(position);
h.eventName.setText(d.getEventName());
Date startDate= d.getStartDate();
Date endDate = d.getEndDate();
long stTime = startDate.getTime();
long now = System.currentTimeMillis();
if(now >= stTime) {h.eventStatus.setText(Html.fromHtml(startedText));}
else {h.eventStatus.setText(Html.fromHtml(upcomingText));}
h.eventStatus.setTag(String.valueOf(position)); // Setting Tag of each TextView to its position to avoid incorrect ayncTask update
new go(h.eventStatus).execute(d.getStartDate()); // starting a thread to update the Text view
return view;
}
public class go extends AsyncTask<Date, Void , Boolean> {
String path;
TextView status;
public go(TextView eventStatus){
this.status=eventStatus;
this.path=eventStatus.getTag().toString();
}
@Override
protected Boolean doInBackground(Date... params) {
Date startDate = params[0];
while(true){
long curTime = System.currentTimeMillis();
long startTime = startDate.getTime();
if (curTime >= startTime) {return true;}
}
}
@Override
protected void onPostExecute(Boolean b) {
if(!status.getTag().toString().equals(path)) return;
if(b!=null && status!=null){
if(b==true) status.setText(Html.fromHtml(startedText));
else status.setText(Html.fromHtml(upcomingText));
}else{
status.setText(Html.fromHtml(upcomingText));
}
}
}
static class Holder{
TextView eventName , eventStatus;
TextView leftTime, rightTime;
}
How to Update the TextView
to started when the current time exceeds the start time. Please Help and suggest a better solution.