com.mitchtodd.myweatherapp.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.mitchtodd.myweatherapp.MainActivity.java

Source

/*
 * Copyright (C) 2014 The Android Open Source Project 
 *
 * 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.mitchtodd.myweatherapp;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.mitchtodd.myweatherapp.data.Weather;
import com.mitchtodd.myweatherapp.data.WeatherModel;
import com.mitchtodd.myweatherapp.listeners.OnGetWeatherFinishedListener;
import com.mitchtodd.myweatherapp.listeners.OnGetWeatherStartedListener;
import com.mitchtodd.myweatherapp.tabs.CurrentWeatherFragment;
import com.mitchtodd.myweatherapp.tabs.WeatherForecastFragment;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

/*
 * The one and only activity for this application.
 */
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

    private final Handler mHandler = new Handler();
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    private WeatherModel mWeatherModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // create single instance of weather model to be used by activity and tab fragments.
        mWeatherModel = new WeatherModel(this);
        mWeatherModel.addOnGetWeatherStartedListener(onGetWeatherStartedListener);
        mWeatherModel.addOnGetWeatherFinishedListener(onGetWeatherFinishedListener);
        mWeatherModel.startWeatherUpdates();
        setLastUpdatedText(true);

        findViewById(R.id.refreshButton).setOnClickListener(onRefreshButtonClickListener);

        // create the adapter that will return a fragment for each of the sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // set up swipe listener
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // for each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            actionBar
                    .addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    protected void onDestroy() {
        // tell weather model to stop updating itself when app is shutdown.
        if (mWeatherModel != null) {
            mWeatherModel.stopWeatherUpdates();
        }

        super.onDestroy();
    }

    @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;
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
            case 0:
                // create tab for Current Weather and pass it instance of weather data model.
                CurrentWeatherFragment currentFragment = new CurrentWeatherFragment();
                currentFragment.setWeatherModel(mWeatherModel);
                return currentFragment;
            case 1:
                // create tab for Weather Forecast and pass it instance of weather data model.
                WeatherForecastFragment forecaseFragment = new WeatherForecastFragment();
                forecaseFragment.setWeatherModel(mWeatherModel);
                return forecaseFragment;
            }
            return null;
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
            case 0:
                return getString(R.string.tab_current);
            case 1:
                return getString(R.string.tab_forecast);
            }
            return null;
        }
    }

    private OnClickListener onRefreshButtonClickListener = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // force weather update from server.
            mWeatherModel.updateWeather();
        }
    };

    private OnGetWeatherStartedListener onGetWeatherStartedListener = new OnGetWeatherStartedListener() {
        @Override
        public void onGetWeatherStarted() {
            mHandler.post(new Runnable() {
                public void run() {
                    handleOnGetWeatherStarted();
                }
            });
        }
    };

    private void handleOnGetWeatherStarted() {
        findViewById(R.id.refreshButton).setVisibility(View.GONE);
        findViewById(R.id.refreshingProgressBar).setVisibility(View.VISIBLE);

        ((TextView) findViewById(R.id.lastUpdatedTextView)).setText(getString(R.string.refreshing_weather));
    }

    private OnGetWeatherFinishedListener onGetWeatherFinishedListener = new OnGetWeatherFinishedListener() {
        @Override
        public void onGetWeatherFinished(final boolean success) {
            mHandler.post(new Runnable() {
                public void run() {
                    handleOnGetWeatherFinished(success);
                }
            });
        }
    };

    private void handleOnGetWeatherFinished(boolean success) {
        findViewById(R.id.refreshingProgressBar).setVisibility(View.GONE);
        findViewById(R.id.refreshButton).setVisibility(View.VISIBLE);

        setLastUpdatedText(success);
    }

    private void setLastUpdatedText(boolean success) {
        // display last updated date/time in view footer.
        // if there is no weather, either from preferences or from server, show "Not Available" message.
        Weather weather = mWeatherModel.getWeather();
        if (weather != null) {
            Date lastUpdated = weather.getLastUpdated();
            if (lastUpdated != null) {
                SimpleDateFormat sdf = new SimpleDateFormat();
                StringBuilder sb = new StringBuilder();
                sb.append(getString(R.string.last_updated));
                sb.append(": ");
                sb.append(sdf.format(lastUpdated));
                ((TextView) findViewById(R.id.lastUpdatedTextView)).setText(sb.toString());
            } else {
                ((TextView) findViewById(R.id.lastUpdatedTextView)).setText(getString(R.string.weather_na));
            }
        } else {
            ((TextView) findViewById(R.id.lastUpdatedTextView)).setText(getString(R.string.weather_na));
        }

        // inform user if data cannot be updated from server.
        if (!success) {
            Toast.makeText(this, getString(R.string.weather_server_error), Toast.LENGTH_SHORT).show();
        }
    }

}