0

Hello I am trying to code the time for Android development

import android.text.format.Time;

This is my code in the MainActivity class within the protected void onCreate.

TextView abc;
abc= (TextView) findViewById(R.id.clockTextView);
abc.setText("Time is " + Time.hour + ":" + Time.minute);

Why do I keep getting the error Cannnot make a static reference to the non-static field Time.hour and how would I fix this? Thanks.

hexacyanide
  • 88,222
  • 31
  • 159
  • 162
brianna_S
  • 13
  • 1
  • 2

2 Answers2

2

Cannnot make a static reference to the non-static field Time.hour

This is because you are trying to access non-static fields in a static way. Time.hour is an instance field (not static), so calling it as Time.hour makes no sense, as you dont have Time instance.

You need to create a Time object and then you can use myTime.hour.

Ajay S
  • 48,003
  • 27
  • 91
  • 111
  • Time.hour and Time.minute are not static field! – BobTheBuilder Mar 10 '13 at 06:47
  • 1
    This is backwards, isn't it? `Time.hour` and `Time.minute` are _not_ static fields. It doesn't matter if they are being accessed from a static method or not; they cannot be accessed without an instance of a `Time` object. The error message even makes the point: "the **non-static** field Time.hour" – Ted Hopp Mar 10 '13 at 06:47
  • Maybe you mix hour and HOUR – BobTheBuilder Mar 10 '13 at 06:48
  • 1
    Your answer is incorrect. Almost all of it! Time.hour is **instance** field, and to access a static fields in non static method you **dont need** to create a class object. – BobTheBuilder Mar 10 '13 at 06:51
  • @baraky I got you I got confuse just reading this `Cannnot make a static reference to the non-static` in whether those were static or instance fiels. Now I was commenting on other answer. Sorry So I could not edit that time..Thanks... – Ajay S Mar 10 '13 at 07:01
2

The hour and minute fields of android.text.format.Time are instance fields. You need to create an instance of Time to access them:

TextView abc;
Time time = new Time(); // initialized to January 1, 1970 in default time zone
time.setToNow();
abc= (TextView) findViewById(R.id.clockTextView);
abc.setText("Time is " + time.hour + ":" + time.minute);
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521