2013-04-24 8 views
0

Как проект для начинающих (я новичок в программировании), я хотел создать простое приложение, в котором будут показаны четыре TextViews: текущее время (часы и минуты), день, дата месяца и год. Это казалось относительно простым, и я исследовал его, и приведенный ниже код - это то, с чем я столкнулся. Кто-нибудь сможет объяснить, почему моя сила приложения закрывается? Я не видел ничего в списке доступных разрешений, в котором говорилось о чтении системного времени. Заранее спасибо. (Примечание: Это единственный класс и макет, который я использую.)Получение системной даты и времени?

MainActivity.java:

package press.linx.calendar; 

import android.os.Bundle; 
import android.app.Activity; 
import android.text.format.Time; 
import android.view.Menu; 
import android.widget.TextView; 

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    TextView day = (TextView)findViewById(R.id.day); 
    TextView month = (TextView)findViewById(R.id.month); 
    TextView year = (TextView)findViewById(R.id.year); 
    TextView time = (TextView)findViewById(R.id.Time); 


    Time today = new Time(Time.getCurrentTimezone()); 
    today.setToNow(); 

    day.setText(today.monthDay);    // Day of the month (0-31) 
    month.setText(today.month);    // Month (0-11) 
    year.setText(today.year);    // Year 
    time.setText(today.format("%k:%M:%S")); // Current time 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

} 

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context=".MainActivity" > 

<TextView 
    android:id="@+id/day" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentTop="true" 
    android:layout_marginLeft="89dp" 
    android:layout_marginTop="32dp" 
    android:text="Large Text" 
    android:textAppearance="?android:attr/textAppearanceLarge" /> 

<TextView 
    android:id="@+id/Time" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentRight="true" 
    android:layout_below="@+id/day" 
    android:layout_marginRight="74dp" 
    android:layout_marginTop="96dp" 
    android:text="TextView" /> 

<TextView 
    android:id="@+id/month" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/day" 
    android:layout_below="@+id/Time" 
    android:layout_marginLeft="38dp" 
    android:layout_marginTop="71dp" 
    android:text="Medium Text" 
    android:textAppearance="?android:attr/textAppearanceMedium" /> 

<TextView 
    android:id="@+id/year" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/month" 
    android:layout_below="@+id/month" 
    android:layout_marginTop="64dp" 
    android:text="Medium Text" 
    android:textAppearance="?android:attr/textAppearanceMedium" /> 

+1

сообщение LogCat ..... – Shiv

+0

пожалуйста показать журнал ошибок LogCat. – Ercan

+0

use Дата d = новая дата(); и получите часы как d.getHours(); – Senthil

ответ

1

Я получаю вашу ошибку.

today.monthDay дает целочисленное значение, и когда вы устанавливаете его в TextView, он ищет ресурс с этим id. Вы должны получить Resources$NotFoundException.

Попробуйте это:

day.setText("" + today.monthDay);    // Day of the month (0-31) 
month.setText("" + today.month);    // Month (0-11) 
year.setText("" + today.year);    // Year 
time.setText("" + today.format("%k:%M:%S")); // Current time 
+0

Это исправлено. Если бы я хотел, чтобы он проводил опрос в течение определенного времени через определенные промежутки времени, он будет обновляться (теперь он показывает только время открытия приложения), как мне это сделать? Заранее спасибо. – ThatGuyThere

+0

U может сделать это с помощью 'CountDownTimer' и в' onFinish() 'метод обновить ваши' Просмотры'. Heres ссылка для использования 'CountDownTimer' http://developer.android.com/reference/android/os/CountDownTimer.html –

-1

Используйте это ява утилиты метод для извлечения текущей даты и времени системы.

Time dtNow = new Time(); 
dtNow.setToNow(); 
String sytem_time_date = dtNow.format("%Y-%m-%d %H:%M:%S"); //use single text view to show 
0

Вы можете использовать Java Util и SimpleDateFormat и даты для той же цели:

long time = System.currentTimeMillis(); 

// Day of the month (0-31) 
SimpleDateFormat sdf = new SimpleDateFormat("d"); 
String day = sdf.format(new Date(time)); 
day.setText(day); 

// month 
sdf = new SimpleDateFormat("M"); 
String month = sdf.format(new Date(time)); 
month.setText(month); 

// year 
sdf = new SimpleDateFormat("y"); 
String year = sdf.format(new Date(time)); 
year.setText(year); 

// time 
sdf = new SimpleDateFormat("K:mm:ss a"); 
String time = sdf.format(new Date(time)); 
time.setText(time); 

Все время Строковые форматы могут быть найдены в http://developer.android.com/reference/java/text/SimpleDateFormat.html#SimpleDateFormat(java.lang.String)

Смежные вопросы