草庐IT

android - 创建一个计时器,以秒、分钟、小时、天为单位显示事件的剩余时间

coder 2023-12-26 原文

Hello I am trying to create a timer wherein it will take the date and time of the event that will happen and convert it into milliseconds and also it will take current time and then subtract the current time from the event time and will calculate the hour minutes seconds and days from it. What I want to do is display those values in a textview but as and when I try and set it in textview it stops working and gives error : - 

    03-25 17:06:03.166: E/AndroidRuntime(993): FATAL EXCEPTION: main
    03-25 17:06:03.166: E/AndroidRuntime(993): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.indianic.planivore/com.indianic.planivore.view.OnSelectingAnEventFromList}: android.content.res.Resources$NotFoundException: String resource ID #0x38
    03-25 17:06:03.166: E/AndroidRuntime(993):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at android.os.Handler.dispatchMessage(Handler.java:99)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at android.os.Looper.loop(Looper.java:137)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at android.app.ActivityThread.main(ActivityThread.java:4745)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at java.lang.reflect.Method.invokeNative(Native Method)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at java.lang.reflect.Method.invoke(Method.java:511)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at dalvik.system.NativeStart.main(Native Method)
    03-25 17:06:03.166: E/AndroidRuntime(993): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x38
    03-25 17:06:03.166: E/AndroidRuntime(993):  at android.content.res.Resources.getText(Resources.java:229)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at android.widget.TextView.setText(TextView.java:3620)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at com.indianic.planivore.view.OnSelectingAnEventFromList.onCreate(OnSelectingAnEventFromList.java:97)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at android.app.Activity.performCreate(Activity.java:5008)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
    03-25 17:06:03.166: E/AndroidRuntime(993):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
    03-25 17:06:03.166: E/AndroidRuntime(993):  ... 11 more

我的布局代码是:-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#B7B1B1" >

    <ImageView
        android:id="@+id/imageOfAnEventAfterSelection"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:contentDescription="@string/imageViewOfAnEvent"
        android:src="@drawable/img_location_image" />

    <ImageView
        android:id="@+id/shareTheEvent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageOfAnEventAfterSelection"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="10dp"
        android:contentDescription="@string/shareOnSocialNetwork"
        android:src="@drawable/ic_shareicon" />

    <ImageView
        android:id="@+id/getSomeInformationOfEvent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageOfAnEventAfterSelection"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/shareTheEvent"
        android:contentDescription="@string/getSomeInformation"
        android:src="@drawable/ic_information" />

    <ImageView
        android:id="@+id/setItToTheFavouriteIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageOfAnEventAfterSelection"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/getSomeInformationOfEvent"
        android:contentDescription="@string/favouriteIconbactch"
        android:src="@drawable/ic_starbatchicon" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageOfAnEventAfterSelection"
        android:layout_margin="5dp"
        android:background="@drawable/bg_clock"
        android:baselineAligned="false"
        android:orientation="horizontal"
        android:weightSum="4" >

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" >

            <ImageView
                android:id="@+id/imgCollenDays"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginTop="20dp"
                android:contentDescription="@string/collonSign"
                android:src="@drawable/collen" />

            <TextView
                android:id="@+id/numberOfDays"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="20dp"
                android:layout_marginTop="10dp"
                android:text="@string/defaultNull"
                android:textColor="#E50303"
                android:textSize="30sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/imgCollenDays"
                android:layout_marginTop="10dp"
                android:gravity="center"
                android:text="@string/days"
                android:textColor="#05660F" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" >

            <ImageView
                android:id="@+id/imgCollenHours"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginTop="20dp"
                android:contentDescription="@string/collonSign"
                android:src="@drawable/collen" />

            <TextView
                android:id="@+id/numberOfHours"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="20dp"
                android:layout_marginTop="10dp"
                android:text="@string/defaultNull"
                android:textColor="#E50303"
                android:textSize="30sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/imgCollenHours"
                android:layout_marginTop="10dp"
                android:gravity="center"
                android:text="@string/hours"
                android:textColor="#05660F" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" >

            <ImageView
                android:id="@+id/imgCollenMinutes"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginTop="20dp"
                android:contentDescription="@string/collonSign"
                android:src="@drawable/collen" />

            <TextView
                android:id="@+id/numberOfMinutes"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="20dp"
                android:layout_marginTop="10dp"
                android:text="@string/defaultNull"
                android:textColor="#E50303"
                android:textSize="30sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/imgCollenMinutes"
                android:layout_marginTop="10dp"
                android:gravity="center"
                android:text="@string/minutes"
                android:textColor="#05660F" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" >

            <TextView
                android:id="@+id/numberOfSeconds"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="20dp"
                android:layout_marginTop="10dp"
                android:text="@string/defaultNull"
                android:textColor="#E50303"
                android:textSize="30sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/numberOfSeconds"
                android:layout_marginTop="2dp"
                android:gravity="center"
                android:text="@string/seconds"
                android:textColor="#05660F" />
        </RelativeLayout>

    </LinearLayout>

    <EditText 
        android:id="@+id/chatEditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:layout_alignParentBottom="true"
        android:hint="@string/EventTextView"/>
</RelativeLayout>

与此相关的 Java 文件如下 我也尝试过使用 fragment ,但它不起作用我哪里出错了任何帮助都欢迎任何尝试,无论它是对还是错,但我会尝试任何想法:-

package com.indianic.planivore.view;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.indianic.planivore.R;

@SuppressLint("SimpleDateFormat")
public class OnSelectingAnEventFromList extends Activity {

    String date;
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    SimpleDateFormat time = new SimpleDateFormat("hh:mm");
    Date eventDate = null;
    Date eventAdditionalTime = null;
    String getEventTime, getEventDate;
    long milliSecondFromDate, milliSecondFromTime, totalmillisecond,
            currentmilliseconds;
    long timeleftinmilliseconds;
    int seconds, minutes, hours, days, weeks;

    TextView tv_days, tv_hour, tv_minutes, tv_seconds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.event_postselection_layout);
//  @Override
//  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    //      Bundle savedInstanceState) {
        // TODO Auto-generated method stub

//      View v = inflater.inflate(R.layout.event_postselection_layout,
//              container, false);

        // Here getting findVievbyID of all the text view to set the time left.
        tv_days = (TextView) findViewById(R.id.numberOfDays);
        tv_hour = (TextView) findViewById(R.id.numberOfHours);
        tv_minutes = (TextView) findViewById(R.id.numberOfMinutes);
        tv_seconds = (TextView) findViewById(R.id.numberOfSeconds);
        Log.d("PRINTING THE DAYS", tv_days.getText().toString());

        Bundle getdata = getIntent().getExtras();

        getEventTime = getdata.getString("timeleftkey");
        getEventDate = getdata.getString("datekey");
        Log.d("kjgkjnbjnknlj", getEventDate + "   " + getEventTime);
        //tv_days.setText("YO");
        // Here I am doing is that the time that I am getting I am converting it
        // to milliseconds so I will add it to the millisecond of the date and
        // will display it in the time left.
        try {
            eventAdditionalTime = time.parse(getEventTime);
            milliSecondFromTime = eventAdditionalTime.getTime();

        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            eventDate = dateFormat.parse(getEventDate);
            milliSecondFromDate = eventDate.getTime();

        } catch (Exception e) {
            // TODO: handle exception
        }

        totalmillisecond = milliSecondFromDate + milliSecondFromTime;
        Log.d("milliSecondFromDate", "" + milliSecondFromDate);
        Log.d("milliSecondFromTime", "" + milliSecondFromTime);

        Calendar cal = Calendar.getInstance();
        currentmilliseconds = cal.getTime().getTime();

        if (currentmilliseconds <= totalmillisecond) {

            while(currentmilliseconds <= totalmillisecond){

                timeleftinmilliseconds = totalmillisecond - currentmilliseconds;
                seconds = (int) (timeleftinmilliseconds / 1000);

                // This below will give me seconds left.
                minutes = seconds / 60;
                seconds = seconds - minutes * 60;
                tv_seconds.setText(seconds);

                // This below will give me minutes left.
                hours = minutes / 60;
                minutes = minutes - hours * 60;
                tv_minutes.setText(minutes);

                // This below will give me hours left.
                days = hours / 24;
                hours = hours - days * 24;
                tv_hour.setText(hours);

                // This below will give me days left.
                weeks = days / 7;
                days = days - weeks * 7;
                tv_days.setText(days);


            }
        } else {
            Toast.makeText(OnSelectingAnEventFromList.this, "LOL YOU MISSED IT", 5000).show();
        }

//      return v;
    }

}

最佳答案

您的整数秒、分和小时等被视为资源。 textView.setText() 有两个签名,一个使用字符串,一个使用 int 来查找资源。这就是您收到错误的原因:

Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x38
03-25 17:06:03.166: E/AndroidRuntime(993):  at android.content.res.Resources.getText(Resources.java:229)

你必须像这样将它们转换成字符串

String.valueOf(days);

更新

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final TextView tv = new TextView(this);
    setContentView(tv);

    int hoursToGo = 0;
    int minutesToGo = 0;
    int secondsToGo = 30;

    int millisToGo = secondsToGo*1000+minutesToGo*1000*60+hoursToGo*1000*60*60;

    new CountDownTimer(millisToGo,1000) {

        @Override
        public void onTick(long millis) {
            int seconds = (int) (millis / 1000) % 60 ;
            int minutes = (int) ((millis / (1000*60)) % 60);
            int hours   = (int) ((millis / (1000*60*60)) % 24);
            String text = String.format("%02d hours, %02d minutes, %02d seconds",hours,minutes,seconds);
            tv.setText(text);
        }

        @Override
        public void onFinish() {
            tv.setText("Kabooom");              
        }
    }.start();

}

}

关于android - 创建一个计时器,以秒、分钟、小时、天为单位显示事件的剩余时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22641728/

有关android - 创建一个计时器,以秒、分钟、小时、天为单位显示事件的剩余时间的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  3. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  4. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  5. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  6. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  7. ruby - 如何使用 RSpec::Core::RakeTask 创建 RSpec Rake 任务? - 2

    如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake

  8. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  9. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  10. ruby-on-rails - Rails - 从另一个模型中创建一个模型的实例 - 2

    我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案

随机推荐