Monday, April 19, 2010

Create a Apps to Show Digital Time in Android

this blog helps to create a simple digital clock in andriod.

Create a Layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView android:id="@+id/countdown" android:layout_width="320dip"
        android:layout_height="120dip" android:text="00:00:00"
        android:textSize="15pt" android:textColor="#00C2FF"
        android:layout_centerInParent="true" />
</RelativeLayout>


Create Activty Class for show the Time

public class MainActivity extends Activity {
    private TextView countdown;
    private Timer timer;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView countdown = (TextView) findViewById(R.id.countdown);
    }

    @Override
    protected void onStart() {
        super.onStart();
        timer = new Timer("DigitalClock");
        Calendar calendar = Calendar.getInstance();

        // Get the Current Time
        final Runnable updateTask = new Runnable() {
            public void run() {
                countdown.setText(getCurrentTimeString()); // shows the current time of the day
//                countdown.setText(getReminingTime()); // shows the remaining time of the day
            }
        };

        // update the UI
        int msec = 999 - calendar.get(Calendar.MILLISECOND);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(updateTask);
            }
        }, msec, 1000);
    }

    @Override
    protected void onStop() {
        super.onStop();
        timer.cancel();
        timer.purge();
        timer = null;
    }
   private String getReminingTime() {
        Calendar calendar = Calendar.getInstance();
        int hour = 23 - calendar.get(Calendar.HOUR_OF_DAY);
        int minute = 59 - calendar.get(Calendar.MINUTE);
        int second = 59 - calendar.get(Calendar.SECOND);
        return String.format("%02d:%02d:%02d", hour, minute, second);
    }



    private String getCurrentTimeString() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        return String.format("%02d:%02d:%02d %02d", hour, minute, second);
    }
}

26 comments:

  1. Hi Ganesan,
    Thanks for your post. I think you declared TextView object "countdown" twice, which will force application to close.

    ReplyDelete
  2. Nice code but there were 2 errors that i just rectified. There was an extra format specifier:

    private String getCurrentTimeString() {
    Calendar calendar = Calendar.getInstance();
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    int minute = calendar.get(Calendar.MINUTE);
    int second = calendar.get(Calendar.SECOND);
    return String.format("%02d:%02d:%02d", hour, minute, second);
    }

    And the TextView has to be public and not private:
    public TextView countdown;

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This code apply my application but arise some error. In this code to set the user permission in the androidManifest.xml give me suggestion for this code.

    ReplyDelete
  5. good code but one exception has occurred during run time...........

    ReplyDelete
  6. It contains 3 errors.
    Make the "countdown" as public.
    Secondly the countdown is declared twice.
    In the String.format("%02d:%02d:%02d %02d") remove one format specifier.
    As it is defined with three variables with 4 format specifier.

    ReplyDelete
  7. @Tapan Rana: Thanks for your advice. I have modified the code and it worked fine. This is entire code for users :)

    import java.util.Calendar;
    import java.util.Timer;
    import java.util.TimerTask;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;

    public class MainActivity extends Activity {
    public TextView countdown;
    public Timer timer;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo);
    countdown = (TextView) findViewById(R.id.countdown);
    }

    @Override
    protected void onStart() {
    super.onStart();
    timer = new Timer("DigitalClock");
    Calendar calendar = Calendar.getInstance();

    // Get the Current Time
    final Runnable updateTask = new Runnable() {
    public void run() {
    countdown.setText(getCurrentTimeString()); // shows the current
    // time of the day
    // countdown.setText(getReminingTime()); // shows the remaining
    // time of the day
    }
    };

    // update the UI
    int msec = 999 - calendar.get(Calendar.MILLISECOND);
    timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
    runOnUiThread(updateTask);
    }
    }, msec, 1000);
    }

    @Override
    protected void onStop() {
    super.onStop();
    timer.cancel();
    timer.purge();
    timer = null;
    }

    public String getReminingTime() {
    Calendar calendar = Calendar.getInstance();
    int hour = 23 - calendar.get(Calendar.HOUR_OF_DAY);
    int minute = 59 - calendar.get(Calendar.MINUTE);
    int second = 59 - calendar.get(Calendar.SECOND);
    return String.format("%02d:%02d:%02d", hour, minute, second);
    }

    public String getCurrentTimeString() {
    Calendar calendar = Calendar.getInstance();
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    int minute = calendar.get(Calendar.MINUTE);
    int second = calendar.get(Calendar.SECOND);
    return String.format("%02d:%02d:%02d", hour, minute, second);
    }
    }

    ReplyDelete
  8. I want that remaining time should show till 9pm of the day.
    Can anyone help.?

    ReplyDelete
  9. I got the answer for show the remaining time till 9pm of the day. Just change the hour count ( int hour = 20 - calendar.get(Calendar.HOUR_OF_DAY);).


    public String getReminingTime() {
    Calendar calendar = Calendar.getInstance();
    int hour = 20 - calendar.get(Calendar.HOUR_OF_DAY);
    int minute = 59 - calendar.get(Calendar.MINUTE);
    int second = 59 - calendar.get(Calendar.SECOND);
    return String.format("%02d:%02d:%02d", hour, minute, second);
    }

    ReplyDelete
  10. how can i get the remaining countdown time in next activity. Please let me know

    ReplyDelete
  11. 이 웹 사이트와 나는이 인터넷 사이트가 정말 유익하다고 생각합니다! 계속 참 으세요! 먹튀검증

    ReplyDelete
  12. Hey, you used 부산달리기

    to write fantastic, but the last several posts have been kinda boring… I miss your tremendous writings. Past several posts are just a little bit out of track! come on!

    ReplyDelete
  13. 사설토토사이트는 개인이 운영하고 있는 토토업체를 말합니다. 먹튀가 많으며 안전하지 못 할 수 있습니다. 그렇기에 저희는 검증 된 가장 안전한 사설토토사이트만을 고집하고 있습니다. 과도한 첫 충전과 이벤트에 속으시면 안 되며 구글에서 단 한번의 먹튀사고도 없는 검증 된 사이트를 이용하셔야합니다. 개인이 운영하는 사설업체인만큼 신중하셔야 합니다
    안전놀이터 .

    ReplyDelete
  14. 최근 수 많은 먹튀업체들이 판을 치고 있기 때문에 사설토토사이트를 이용하시려는 방문자 분들께서는 검증 된 업체만을 선별하여 이용하시는 것을 권해드립니다. 가장 안전한 토토사이트를 추천해드리는 토토식스의 안전가이드를 따르신다면 즐거운 스포츠토토를 즐기실 수 있다고 확신합니다 사설토토사이트 .

    ReplyDelete
  15. Hi there friends, pleasant post and fastidious urging commented here, I am actually enjoying by these. 립카페

    ReplyDelete
  16. Wow, incredible blog format! How long have you ever been blogging for? you make running a blog glance easy. The overall glance of your site is excellent, let alone the content material! 외국인출장

    ReplyDelete
  17. I like to recommend exclusively fine plus efficient information and facts, hence notice its very informative and your blog is really good 메이저검증업체

    ReplyDelete
  18. This post is invaluable this web site is genuinely nice and the people are 토토추천

    ReplyDelete
  19. I'll come and read every day. It's really nice to have a place like this Thank you for sharing your thoughts. I really appreciate your 메이저사이트

    ReplyDelete
  20. This is a very impressive subject. Thank you for always. I have been reading your article interestingly. If possible, please visit my website to read my posts and leave comments. Have a nice day! 바카라사이트 What you wrote was very helpful to me. Thank you. Actually, I run a site similar to you. If you have time, could you visit my site? Please leave your comments after reading what I wrote. If you do so, I will actively reflect your opinion. I think it will be a great help to run my site. Have a good day.


    ReplyDelete
  21. I finally found what I was looking for! I'm so happy. 우리카지노


    ReplyDelete
  22. Qi Coins Trick! Cheating The 먹튀사이트! - Stardew Valley

    ReplyDelete
  23. That's exactly what I've been looking for
    검증카지노

    Your information was very useful to me.
    온라인카지노

    ReplyDelete
  24. Thanks for sharing helpful information. Appconsultio offers ongoing maintenance and support services to keep the apps up-to-date and functioning smoothly as new versions of the Android OS are released or as the app's requirements evolve. Our Mobile Application Developers in Pune have crafted an innovative app that is revolutionizing the way people interact with technology.

    ReplyDelete