Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8599231
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T01:21:10+00:00 2026-06-12T01:21:10+00:00

I did everything i could to fix this, but never succeeded, i look around

  • 0

I did everything i could to fix this, but never succeeded, i look around the web too, but didn’t find what i’m looking for.

So. I’m working on a stopwatch application, and i want it to show milliseconds, but i’m having trouble getting the right digest shown, cause i only want it to show centiseconds, i mean two digits, going from 00 to 99 and then 1 second has past.

When i run the app with the code below, it looks like in the emulator, that i works, (can’t quite tell, because the emulator is slow and laggy) but when i run it on my galaxy nexus 4.1.1 i get force close.

Any help will be much appreciated

Here’s the code for the milliseconds string:

milliseconds = String.valueOf((long)time);
    if(milliseconds.length()==3){
        milliseconds = "0"+milliseconds;
    }
    if(milliseconds.length()<=1){
        milliseconds = "00";
    }
    milliseconds = milliseconds.substring(milliseconds.length()-3,   milliseconds.length()-1);

Full java:

package com.tutorial.stopwatch;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.app.Activity;  
import android.content.res.Configuration;
import android.widget.LinearLayout;
import android.widget.TextView;  
import android.graphics.Typeface;  
import android.os.Bundle;  
import android.util.DisplayMetrics;  
import android.util.TypedValue;
import android.view.View;  
import android.widget.Button;  

public class MainActivity extends Activity {

    private TextView tempTextView; //Temporary TextView
    private Button tempBtn; //Temporary Button 
    private Handler mHandler = new Handler();
    private long startTime;
    private long elapsedTime;
    private final int REFRESH_RATE = 100;
    private String hours,minutes,seconds,milliseconds;
    private long secs,mins,hrs,msecs;
    private boolean stopped = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkScreenDensity();

        /*-------Setting the TextView Fonts-----------*/  

        Typeface fonttimer = Typeface.createFromAsset(getAssets(), "roboto.ttf");
        tempTextView = (TextView) findViewById(R.id.timer);  
        tempTextView.setTypeface(fonttimer);
        tempTextView = (TextView) findViewById(R.id.timerMs);  
        tempTextView.setTypeface(fonttimer);
        tempTextView = (TextView) findViewById(R.id.timerHs);  
        tempTextView.setTypeface(fonttimer);

        Typeface font = Typeface.createFromAsset(getAssets(), "roboto.ttf");
        tempTextView = (TextView) findViewById(R.id.backgroundText);  
        tempTextView.setTypeface(font);  
        Button tempBtn = (Button)findViewById(R.id.startButton);  
        tempBtn.setTypeface(font);  
        tempBtn = (Button)findViewById(R.id.resetButton);  
        tempBtn.setTypeface(font);  
        tempBtn = (Button)findViewById(R.id.stopButton);  
        tempBtn.setTypeface(font);  

    }


    private void checkScreenDensity(){  
        tempTextView = (TextView)findViewById(R.id.backgroundText);  
        switch (getResources().getDisplayMetrics().densityDpi) {  
        case DisplayMetrics.DENSITY_LOW:  
            tempTextView.setVisibility(View.GONE);  
            break;  
        case DisplayMetrics.DENSITY_MEDIUM:  
            tempTextView.setVisibility(View.GONE);  
            break;  
        case DisplayMetrics.DENSITY_HIGH:  
            tempTextView.setVisibility(View.VISIBLE);  
            break;  
        }  
    }  

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }



    //---------- on click procedures - id from layout.xml -----------

    public void startClick (View view){
        showStopButton();
        if(stopped){
            startTime = System.currentTimeMillis() - elapsedTime;
        }
        else{
            startTime = System.currentTimeMillis();
        }
        mHandler.removeCallbacks(startTimer);
        mHandler.postDelayed(startTimer, 0);
    }

    public void stopClick (View view){
        hideStopButton();
        mHandler.removeCallbacks(startTimer);
        stopped = true;
    }

    public void resetClick (View view){
        hideStopButton();
        mHandler.removeCallbacks(startTimer);
        stopped = false;
        ((TextView)findViewById(R.id.timer)).setText("00:00");
        ((TextView)findViewById(R.id.timerMs)).setText(":00");
        ((TextView)findViewById(R.id.timerHs)).setText("00:");
    }

    //---------- Button change (start/reset to stop button)
    private void showStopButton(){
        ((Button)findViewById(R.id.startButton)).setVisibility(View.GONE);
        ((Button)findViewById(R.id.resetButton)).setVisibility(View.VISIBLE);
        ((Button)findViewById(R.id.stopButton)).setVisibility(View.VISIBLE);
    }

    private void hideStopButton(){
        ((Button)findViewById(R.id.startButton)).setVisibility(View.VISIBLE);
        ((Button)findViewById(R.id.resetButton)).setVisibility(View.VISIBLE);
        ((Button)findViewById(R.id.stopButton)).setVisibility(View.GONE);
    }

    //-------- time from MiliSeconds to regular time ---------------------------------

    private void updateTimer (float time){
        secs = (long)(time/1000);
        mins = (long)((time/1000)/60);
        hrs = (long)(((time/1000)/60)/60);

        /* Setting the timer text to the elapsed time */
        ((TextView)findViewById(R.id.timerHs)).setText(hours + ":");
        ((TextView)findViewById(R.id.timer)).setText(minutes + ":" + seconds);
        ((TextView)findViewById(R.id.timerMs)).setText(":" + milliseconds);

        /* Convert the seconds to String
         * and format to ensure it has
         * a leading zero when required
         */
        secs = secs % 60;
        seconds=String.valueOf(secs);
        if(secs == 0){
            seconds = "00";
        }
        if(secs <10 && secs > 0){
            seconds = "0"+seconds;
        }

        /* Convert the minutes to String and format the String */

        mins = mins % 60;
        minutes=String.valueOf(mins);
        if(mins == 0){
            minutes = "00";
        }
        if(mins <10 && mins > 0){
            minutes = "0"+minutes;
        }

        /* Convert the hours to String and format the String */

        hours=String.valueOf(hrs);
        if(hrs == 0){
            hours = "00";
        }
        if(hrs <10 && hrs > 0){
            hours = "0"+hours;
        }

        /* milliseconds  */

        milliseconds = String.valueOf((long)time);
        if(milliseconds.length()==3){
            milliseconds = "0"+milliseconds;
        }
        if(milliseconds.length()<=1){
            milliseconds = "00";
        }
        milliseconds = milliseconds.substring(milliseconds.length()-3,   milliseconds.length()-1);




    }

    //------------- Timer Runnnable -----------------------------------------------------------

    private Runnable startTimer = new Runnable() {
           public void run() {
               elapsedTime = System.currentTimeMillis() - startTime;
               updateTimer(elapsedTime);
               mHandler.postDelayed(this,REFRESH_RATE);
            }
        };

    //------------------ screen orientation fix -----------------------------------------------------------

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                TextView timer = (TextView) findViewById(R.id.timer);
                timer.setTextSize(TypedValue.COMPLEX_UNIT_SP, 90);
                TextView timerMs = (TextView) findViewById(R.id.timerMs);
                timerMs.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40);

            }
            else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                TextView timer = (TextView) findViewById(R.id.timer);
                timer.setTextSize(TypedValue.COMPLEX_UNIT_SP, 70);
                TextView timerMs = (TextView) findViewById(R.id.timerMs);
                timerMs.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);

            }
        }



}

UPDATE:

I edited the code to fit my layout, but i crashes:

private void updateTimer (long time) {
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(time);

    // This will output one string in Hour:Minute:Seconds: with zeroes added
    String h = String.format("%1$tH", c);
    String ms = String.format("%1$tM:%1$tS", c);
    // Unfortunately, theres no format specifier for centiseconds, so we'll have
    // to make do with the substring of ms
    String cs  = String.format("%1$L").substring(0,2);

    String printMe = h + ms + cs;

    /* Setting the timer text to the elapsed time */
        ((TextView)findViewById(R.id.timerHs)).setText(h);
        ((TextView)findViewById(R.id.timer)).setText(ms);
        ((TextView)findViewById(R.id.timerMs)).setText(cs);


}

Log:

09-28 19:32:29.986: D/dalvikvm(1832): GC_FOR_ALLOC freed 42K, 4% free 8005K/8259K, paused 112ms, total 118ms
09-28 19:32:30.008: I/dalvikvm-heap(1832): Grow heap (frag case) to 9.331MB for 1536016-byte allocation
09-28 19:32:30.116: D/dalvikvm(1832): GC_CONCURRENT freed <1K, 4% free 9504K/9799K, paused 33ms+17ms, total 109ms
09-28 19:32:30.426: D/dalvikvm(1832): GC_FOR_ALLOC freed 3K, 2% free 9864K/10055K, paused 40ms, total 41ms
09-28 19:32:30.756: D/gralloc_goldfish(1832): Emulator without GPU emulation detected.
09-28 19:32:41.536: D/AndroidRuntime(1832): Shutting down VM
09-28 19:32:41.588: W/dalvikvm(1832): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-28 19:32:41.646: E/AndroidRuntime(1832): FATAL EXCEPTION: main
09-28 19:32:41.646: E/AndroidRuntime(1832): java.util.MissingFormatArgumentException: Format specifier: 1$L
09-28 19:32:41.646: E/AndroidRuntime(1832):     at java.util.Formatter.getArgument(Formatter.java:1109)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at java.util.Formatter.doFormat(Formatter.java:1074)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at java.util.Formatter.format(Formatter.java:1040)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at java.util.Formatter.format(Formatter.java:1009)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at java.lang.String.format(String.java:1998)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at java.lang.String.format(String.java:1972)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at com.tutorial.stopwatch.MainActivity.updateTimer(MainActivity.java:138)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at com.tutorial.stopwatch.MainActivity.access$3(MainActivity.java:129)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at com.tutorial.stopwatch.MainActivity$1.run(MainActivity.java:155)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at android.os.Handler.handleCallback(Handler.java:615)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at android.os.Looper.loop(Looper.java:137)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at android.app.ActivityThread.main(ActivityThread.java:4745)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at java.lang.reflect.Method.invokeNative(Native Method)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at java.lang.reflect.Method.invoke(Method.java:511)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-28 19:32:41.646: E/AndroidRuntime(1832):     at dalvik.system.NativeStart.main(Native Method)

Thanks!!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T01:21:11+00:00Added an answer on June 12, 2026 at 1:21 am

    Why are you dealing with your times in strings? this will only cause you pain and suffering 🙂 Java formatter has a much better way to deal with times:

    // Note the long type here - that's what you're passing in anyway, best make it
    // official
    private void updateTimer (long time) {
        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        c.setTimeMillis(time);
    
        // This will output one string in Hour:Minute:Seconds: with zeroes added
        String hms = String.format("%1$tH:%1$tM:%1$tS:", c);
        // Unfortunately, theres no format specifier for centiseconds, so we'll have
        // to make do with the substring of ms
        String cs  = String.format("%1$tL", c).substring(0,2);
    
        String printMe = hms + cs
    }
    

    See the formatter for more

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I did everything I could to make it happen, but without success. The problem
I already searched for everything I could, but this annoying error is still there.
I did everything in Windows XP 32bit-with 4GB RAM, but thought why not install
I did everything I could to alert something after submitting a button which has
Disclaimer: first month of developing with rails, but I have read everything I could
I did everything as it is written in the book of Vaswani V. -
I believe that I did everything necessary to change my app for ipad (was
In my app, I am upgrading from Cocos2D version 1.10->2.0-rc0a. So I did everything
I did heroku create and pushed a working rails app to the server. Everything
I just did a fresh install of Apache server 2.2. Everything works. When I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.