Java tutorial
/* * Copyright (c) 2014 Yehezkel (Zack) Yovel * * 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 zack.yovel.clear.controller.foreground; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import zack.yovel.clear.infrastructure.model.datapoints.WeatherReport; import zack.yovel.clear.infrastructure.persist.IWeatherPersist; public abstract class WeatherFragment extends Fragment implements IWeatherPersist.IWeatherInflatedListener { protected WeatherReport getWeatherReport() { WeatherReport output = null; IDataProvider<WeatherReport> dataProvider = getDataProvider(); if (dataProvider != null) { output = dataProvider.getData(); } return output; } private IDataProvider<WeatherReport> getDataProvider() { FragmentActivity activity = getActivity(); try { return (IDataProvider<WeatherReport>) activity; } catch (ClassCastException e) { throw new RuntimeException( activity.getClass().getName() + " must implement " + IDataProvider.class.getName()); } } @Override public void onActivityCreated(Bundle savedInstanceState) { WeatherReport weatherReport = getWeatherReport(); if (weatherReport != null) { displayWeatherReport(weatherReport); } Activity activity = getActivity(); if (activity.getClass().equals(MainActivity.class)) { ((MainActivity) activity).addListener(this); } super.onActivityCreated(savedInstanceState); } @Override public void onPause() { Activity activity = getActivity(); if (activity != null && activity.getClass().equals(MainActivity.class)) { ((MainActivity) activity).removeListener(this); } super.onPause(); } @Override public void onWeatherReportReady(WeatherReport weatherReport) { displayWeatherReport(weatherReport); } protected abstract void displayWeatherReport(WeatherReport weatherReport); @Override public void onReadFailed() { } /** * This interface defines a data provider of some sort. * The type of the data will be determined by the implementation. * <p/> * In Clear! it is meant to define a unified method for activities that * host a sub-class of the WeatherFragment class to provide weather * info to the fragment. * * @param <T> */ public interface IDataProvider<T> { T getData(); } }