Android Open Source - Weather Main Activity






From Project

Back to project page Weather.

License

The source code is released under:

Apache License

If you think the Android project Weather listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.volitic.weather;
/*from   w w  w.ja  va 2 s.c  om*/
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import java.io.InputStream;

public class MainActivity extends Activity implements Network.Downloader, XmlParser.Parser {

    MenuItem refresh_button;
    boolean progress_wheel_available;
    WeatherFragment weather_fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // request use of loading spinner in action bar
        progress_wheel_available = requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new DefaultFragment())
                    .commit();
        }

        weather_fragment = new WeatherFragment();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);
        refresh_button = menu.findItem(R.id.action_refresh);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.action_refresh) {
            sendWeatherRequest();

        } else if (id == R.id.action_about) {
            AboutDialog a = new AboutDialog();
            a.show( getFragmentManager(),"about_dialog_tag");

        } else if (id == R.id.action_settings) {
            Intent settings_intent = new Intent(getApplicationContext(), SettingsActivity.class);
            startActivity(settings_intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void displayBusyLooper(boolean show){

        if( show && progress_wheel_available){
            refresh_button.setVisible(false);
            setProgressBarIndeterminateVisibility(true);
        } else if (progress_wheel_available) {
            refresh_button.setVisible(true);
            setProgressBarIndeterminateVisibility(false);
        }
    }

    private void sendWeatherRequest(){

        String weather_url = getUrl();

        if( weather_url.isEmpty() ){
            return; //unable to determine request
        }

        // show spinner in action bar to represent network activity
        displayBusyLooper(true);

        Network net = new Network(this, getBaseContext()); //todo move this - no need to create a new instance every time
        net.download( weather_url );
    }

    private String getUrl(){

        SharedPreferences shared_prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        final String base_url = "http://api.openweathermap.org/data/2.5/weather?mode=xml";

        String city = shared_prefs.getString("location_manual","");

        if( city.isEmpty() ){

            Toast.makeText(
                    getApplicationContext(),
                    getString(R.string.no_location_error),
                    Toast.LENGTH_LONG
                    ).show();

            //unable to make a request to the api without a location
            return "";
        }


        String build_string =
                base_url
                        + "&q=" + city
                        + "&units=" + shared_prefs.getString("display_units","metric");
        /*
        have not acquired api key yet
        build_string += "&APPID=" + api_key;
        */

        return build_string;
    }

    @Override
    public void downloadSucceeded( InputStream stream ) {

        //pass results to parser
        XmlParser parser = new XmlParser(this); //todo move this - no need to create a new instance every time
        parser.parse(stream);
     }

    @Override
    public void downloadFailed() {

        displayBusyLooper(false);

        //inform the user
        Toast.makeText(
                getApplicationContext(),
                getString(R.string.download_error),
                Toast.LENGTH_LONG
                ).show();

    }



    @Override
    public void parseFailed() {
        Toast.makeText(
                getApplicationContext(),
                getString(R.string.parse_error),
                Toast.LENGTH_LONG
        ).show();
        displayBusyLooper(false);
    }

    @Override
    public void parseSucceeded(Weather weather) {

        weather_fragment.updateConditions( weather );

        getFragmentManager().beginTransaction()
                .replace(R.id.container, weather_fragment)
                .commit();

        displayBusyLooper(false);
    }

    /**
     * The fragment that displays the current weather data.
     */
    public static class WeatherFragment extends Fragment {

        Weather current_conditions;
        public static final String WEATHER = "weather";

        public WeatherFragment(){}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            View content = inflater.inflate(R.layout.fragment_weather, container, false);

            if( savedInstanceState != null ){
                try {
                    updateConditions((Weather)savedInstanceState.getParcelable(WEATHER));
                } catch (ClassCastException e){
                    //request new weather forecast
                }
            }
            return content;
        }

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

            //in case updateConditions was called before onCreateView was able to complete.
            if(current_conditions != null ){
                updateUI();
            }
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            outState.putParcelable(WEATHER, current_conditions);
            super.onSaveInstanceState(outState);
        }

        public void updateConditions(Weather weather){
            current_conditions = weather;
            updateUI();
        }

        private void updateUI(){

            View root_view = getView();

            if(root_view == null){
                //too soon! onCreateView has not had a chance to execute yet.
                return;
            }


            ((TextView)root_view.findViewById(R.id.text_temperature_value))
                    .setText(String.format("%.1f", current_conditions.get(Weather.number.TEMPERATURE)));

            switch (current_conditions.getUnits()){
                case METRIC:
                    ((TextView)root_view.findViewById(R.id.text_temperature_units)).setText(R.string.units_celsius);
                    break;
                case IMPERIAL:
                    ((TextView)root_view.findViewById(R.id.text_temperature_units)).setText(R.string.units_fahrenheit);
                    break;
                case SI:
                    ((TextView)root_view.findViewById(R.id.text_temperature_units)).setText(R.string.units_kelvin);
            }

            ((TextView)root_view.findViewById(R.id.text_temperature_high_value))
                    .setText(String.format("%.1f", current_conditions.get(Weather.number.TEMPERATURE_HIGH)));

            ((TextView)root_view.findViewById(R.id.text_temperature_low_value))
                    .setText(String.format("%.1f", current_conditions.get(Weather.number.TEMPERATURE_LOW)));

            ((TextView)root_view.findViewById(R.id.text_summary))
                    .setText(current_conditions.get(Weather.text.QUALITATIVE_SUMMARY).toUpperCase());

            ((TextView)root_view.findViewById(R.id.text_location_value))
                    .setText(current_conditions.get(Weather.text.LOCATION));

            ((TextView)root_view.findViewById(R.id.text_humidity_value))
                    .setText(String.format("%.0f", current_conditions.get(Weather.number.HUMIDITY)));

            ((TextView)root_view.findViewById(R.id.text_pressure_value))
                    .setText(String.format("%.0f", current_conditions.get(Weather.number.PRESSURE)));

            ((TextView)root_view.findViewById(R.id.text_precipitation_value))
                    .setText(String.format("%.1f", current_conditions.get(Weather.number.PRECIPITATION)));

            ((TextView)root_view.findViewById(R.id.text_sunrise_value))
                    .setText(
                            Time.secondsToTime(
                                    current_conditions.get( Weather.number.SUNRISE),
                                             Integer.parseInt( PreferenceManager
                                                    .getDefaultSharedPreferences(getActivity().getApplicationContext())
                                                    .getString("timezone_utc_offset", "0"))));

            ((TextView)root_view.findViewById(R.id.text_sunset_value))
                    .setText(
                            Time.secondsToTime(
                                    current_conditions.get( Weather.number.SUNSET),
                                             Integer.parseInt(PreferenceManager
                                                    .getDefaultSharedPreferences(getActivity().getApplicationContext())
                                                    .getString("timezone_utc_offset", "0"))));

            ((TextView)root_view.findViewById(R.id.text_wind_speed_value))
                    .setText(String.format("%.1f", current_conditions.get(Weather.number.WIND_SPEED)));

            ((TextView)root_view.findViewById(R.id.text_wind_direction_value))
                    .setText(current_conditions.get(Weather.text.WIND_BEARING));
        }

    }

    /**
     * The fragment shown when there is no weather data available.
     */
    public static class DefaultFragment extends Fragment {

        public DefaultFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_main, container, false);
        }
    }

}




Java Source Code List

com.volitic.weather.AboutDialog.java
com.volitic.weather.AutoCompleteCursorAdapter.java
com.volitic.weather.AutoCompletePreference.java
com.volitic.weather.DatabaseHelper.java
com.volitic.weather.MainActivity.java
com.volitic.weather.Network.java
com.volitic.weather.SettingsActivity.java
com.volitic.weather.Time.java
com.volitic.weather.Weather.java
com.volitic.weather.XmlParser.java