Substrates Milliseconds good numbers

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  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  0){
            minutes = "0"+minutes;
        }

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

        hours=String.valueOf(hrs);
        if(hrs == 0){
            hours = "00";
        }
        if(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!!

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

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动开发 » Substrates Milliseconds good numbers

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录