Java tutorial
/* * Copyright (C) 2016 The Android Open Source Project * 1990chriswang1990@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.upenn.chriswang1990.sunshine; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.upenn.chriswang1990.sunshine.data.WeatherContract; public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { static final String DETAIL_URI = "URI"; private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp"; private String forecastStr; private Uri mUri; private static final int DETAIL_LOADER = 0; private static final String[] DETAIL_COLUMNS = { WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID, WeatherContract.WeatherEntry.COLUMN_DATE, WeatherContract.WeatherEntry.COLUMN_DATE_UNIX_TIMESTAMP, WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, WeatherContract.WeatherEntry.COLUMN_HUMIDITY, WeatherContract.WeatherEntry.COLUMN_PRESSURE, WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, WeatherContract.WeatherEntry.COLUMN_DEGREES, WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, WeatherContract.LocationEntry.COLUMN_TIMEZONE_ID, WeatherContract.LocationEntry.COLUMN_CITY_NAME }; static final int COL_WEATHER_ID = 0; static final int COL_WEATHER_DATE = 1; static final int COL_WEATHER_DATE_UNIX = 2; static final int COL_WEATHER_DESC = 3; static final int COL_WEATHER_MAX_TEMP = 4; static final int COL_WEATHER_MIN_TEMP = 5; public static final int COL_WEATHER_HUMIDITY = 6; public static final int COL_WEATHER_PRESSURE = 7; public static final int COL_WEATHER_WIND_SPEED = 8; public static final int COL_WEATHER_DEGREES = 9; public static final int COL_WEATHER_CONDITION_ID = 10; static final int COL_TIMEZONE_ID = 11; static final int COL_CITY_NAME = 12; private ImageView mIconView; private TextView mDayView; private TextView mDateView; private TextView mDescriptionView; private TextView mHighTempView; private TextView mLowTempView; private TextView mHumidityView; private TextView mHumidityLabelView; private TextView mWindView; private TextView mWindLabelView; private TextView mPressureView; private TextView mCityNameView; private TextView mPressureLabelView; public DetailFragment() { setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle arguments = getArguments(); if (arguments != null) { mUri = arguments.getParcelable(DetailFragment.DETAIL_URI); } else { mUri = getDefaultUri(); } View rootView = inflater.inflate(R.layout.fragment_detail, container, false); mIconView = (ImageView) rootView.findViewById(R.id.detail_icon); mDateView = (TextView) rootView.findViewById(R.id.detail_date_textview); mDescriptionView = (TextView) rootView.findViewById(R.id.detail_forecast_textview); mHighTempView = (TextView) rootView.findViewById(R.id.detail_high_textview); mLowTempView = (TextView) rootView.findViewById(R.id.detail_low_textview); mHumidityView = (TextView) rootView.findViewById(R.id.detail_humidity_textview); mHumidityLabelView = (TextView) rootView.findViewById(R.id.detail_humidity_label_textview); mWindView = (TextView) rootView.findViewById(R.id.detail_wind_textview); mWindLabelView = (TextView) rootView.findViewById(R.id.detail_wind_label_textview); mPressureView = (TextView) rootView.findViewById(R.id.detail_pressure_textview); mPressureLabelView = (TextView) rootView.findViewById(R.id.detail_pressure_label_textview); mCityNameView = (TextView) rootView.findViewById(R.id.detail_city_name); return rootView; } private void finishCreatingMenu(Menu menu) { // Retrieve the share menu item MenuItem menuItem = menu.findItem(R.id.action_share); menuItem.setIntent(createShareForecastIntent()); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Inflate the menu; this adds items to the action bar if it is present. if (getActivity() instanceof DetailActivity) { inflater.inflate(R.menu.detail_fragment, menu); finishCreatingMenu(menu); } } private Intent createShareForecastIntent() { Intent shareIntent = new Intent(Intent.ACTION_SEND); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); } else { shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); } shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, forecastStr + FORECAST_SHARE_HASHTAG); return shareIntent; } @Override public void onActivityCreated(Bundle savedInstanceState) { getLoaderManager().initLoader(DETAIL_LOADER, null, this); super.onActivityCreated(savedInstanceState); } void onLocationChanged() { // replace the uri, since the location has changed mUri = getDefaultUri(); getLoaderManager().restartLoader(DETAIL_LOADER, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (null != mUri) { // Now create and return a CursorLoader that will take care of // creating a Cursor for the data being displayed. return new CursorLoader(getActivity(), mUri, DETAIL_COLUMNS, null, null, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { // Read weather condition ID from cursor int weatherId = data.getInt(COL_WEATHER_CONDITION_ID); mIconView.setImageResource(Utility.getArtResourceForWeatherCondition(weatherId)); //read city name and update String cityName = data.getString(COL_CITY_NAME); mCityNameView.setText(cityName); mCityNameView.setContentDescription(getString(R.string.a11y_city_name, cityName)); // Read date from cursor and update views for day of week and date long unixTimestamp = data.getLong(COL_WEATHER_DATE_UNIX); String timezoneID = data.getString(COL_TIMEZONE_ID); String dateText = Utility.getFullFriendlyDayString(getActivity(), unixTimestamp, timezoneID); mDateView.setText(dateText); // Read description from cursor and update view String description = Utility.getStringForWeatherCondition(getActivity(), weatherId); mDescriptionView.setText(description); mDescriptionView.setContentDescription(getString(R.string.a11y_forecast, description)); // For accessibility, add a content description to the icon field. Because the ImageView // is independently focusable, it's better to have a description of the image. Using // null is appropriate when the image is purely decorative or when the image already // has text describing it in the same UI component. mIconView.setContentDescription(getString(R.string.a11y_forecast_icon, description)); // Read high temperature from cursor and update view double high = data.getDouble(COL_WEATHER_MAX_TEMP); String highString = Utility.formatTemperature(getActivity(), high); mHighTempView.setText(highString); mHighTempView.setContentDescription(getString(R.string.a11y_high_temp, highString)); // Read low temperature from cursor and update view double low = data.getDouble(COL_WEATHER_MIN_TEMP); String lowString = Utility.formatTemperature(getActivity(), low); mLowTempView.setText(lowString); mLowTempView.setContentDescription(getString(R.string.a11y_low_temp, lowString)); // Read humidity from cursor and update view float humidity = data.getFloat(COL_WEATHER_HUMIDITY); mHumidityView.setText(getString(R.string.format_humidity, humidity)); mHumidityView.setContentDescription(getString(R.string.a11y_humidity, mHumidityView.getText())); mHumidityLabelView.setContentDescription(mHumidityView.getContentDescription()); // Read wind speed and direction from cursor and update view float windSpeedStr = data.getFloat(COL_WEATHER_WIND_SPEED); float windDirStr = data.getFloat(COL_WEATHER_DEGREES); mWindView.setText(Utility.getFormattedWind(getActivity(), windSpeedStr, windDirStr)); mWindView.setContentDescription(getString(R.string.a11y_wind, mWindView.getText())); mWindLabelView.setContentDescription(mWindView.getContentDescription()); // Read pressure from cursor and update view float pressure = data.getFloat(COL_WEATHER_PRESSURE); mPressureView.setText(getString(R.string.format_pressure, pressure)); mPressureView.setContentDescription(getString(R.string.a11y_pressure, mPressureView.getText())); mPressureLabelView.setContentDescription(mPressureView.getContentDescription()); forecastStr = String.format(getContext().getString(R.string.format_share_string), cityName, dateText, description, highString, lowString); AppCompatActivity activity = (AppCompatActivity) getActivity(); Toolbar toolbarView = (Toolbar) getView().findViewById(R.id.toolbar); // We need to start the enter transition after the data has loaded if (activity instanceof DetailActivity) { activity.supportStartPostponedEnterTransition(); if (null != toolbarView) { activity.setSupportActionBar(toolbarView); activity.getSupportActionBar().setDisplayShowTitleEnabled(false); activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } else { if (null != toolbarView) { Menu menu = toolbarView.getMenu(); if (null != menu) menu.clear(); toolbarView.inflateMenu(R.menu.detail_fragment); finishCreatingMenu(toolbarView.getMenu()); } } } } @Override public void onLoaderReset(Loader<Cursor> loader) { } public Uri getDefaultUri() { long date = Utility.normalizeDate(System.currentTimeMillis() / 1000, Utility.getTimezoneID(getActivity())); String newLocation = Utility.getPreferredLocation(getActivity()); return WeatherContract.WeatherEntry.buildWeatherLocationWithDate(newLocation, date); } }