nexus490
nexus490

Reputation: 817

Use of calendar class

I have created an xml layout which is in effect a grid. I need to use it as a calendar and have read about the calendar class but i've been unable to get any of the code it suggests to work.

How would i go about displaying the current year,month and days in the various text views?

This is what i have so far:

Calendar c = Calendar.getInstance(); 
    int month = c.get(Calendar.MONTH);

    String month_name = Integer.toString(month);

    TextView monthdisp = (TextView) findViewById(R.id.month_disp);

    monthdisp.setText(month_name);

    setContentView(R.layout.main);

However a null pointer excpetion is generated at monthdisp.setText(month_name);

Upvotes: 2

Views: 13192

Answers (2)

Reinier
Reinier

Reputation: 3876

See the Android Developers guide To get the current year, month and days you'd use the following:

Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR); // get the current year
int month = cal.get(Calendar.MONTH); // month...
int day = cal.get(Calendar.DAY_OF_MONTH); // current day in the month

// sets your textview to e.g. 2012/03/15 for today
textview.setText("Year / month / day: "+ year + "/" + month + "/" + day);

Alternatively, you can use SimpleDateFormat like so:

// set-up the desired formatting
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();

Date now = cal.getTime(); // set the current datetime in a Date-object

// SimpleDateFormat.format( Date date ) returns a formatted string
// with the predefined format
String mTimeString = sdf.format( now ); // contains yyyy-MM-dd (e.g. 2012-03-15 for March 15, 2012)

TextView textView = new TextView(this);
textView.setText( mTimeString );

The other way around also works:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

String mDateString = "14-05-2012";
Date mDate = sdf.parse( mDateString ); // returns a Date-object
                                       // with date set to May 14, 2012

Upvotes: 4

Roberto Tyley
Roberto Tyley

Reputation: 25304

The other answers here provide good info about the Calendar class and date/time manipulation, but that's not why your code is throwing a NullPointerException:

TextView monthdisp = (TextView) findViewById(R.id.month_disp);

monthdisp.setText(month_name); // NPE here indicates monthdisp is null

Calling findViewById(R.id.month_disp) returned null. This is probably because you haven't inflated your view yet, or month_disp just isn't in your layout.

Typically, view inflation occurs in the Activity.onCreate() method, and you can do it in several ways, for instance setContentView(). Check that you are doing this before calling findViewById(), and that the layout you are inflating actually has that view in it.

Upvotes: 2

Related Questions