Android Open Source - Weather Forecast Fragment






From Project

Back to project page Weather.

License

The source code is released under:

GNU General Public 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.captainchloride.weather;
/*from  w  w w .  ja  v a 2 s  .  com*/
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
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.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by captainchloride on 8/17/14.
 */
public class ForecastFragment extends Fragment {

    private ArrayAdapter<String> forecastAdapter;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId() == R.id.action_refresh)
        {
            updateWeather();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void updateWeather()
    {
        FetchWeatherTask weatherTask = new FetchWeatherTask();
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String location = preferences.getString(getString(R.string.pref_location_key), getString(R.string.pref_location_default));
        weatherTask.execute(location);
    }

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.forecastfragment, menu);
    }

    public ForecastFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_my, container, false);
        ListView forecastView = (ListView) rootView.findViewById(R.id.ForecastList);
        forecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.forecast_text_view_layout, R.id.forecastTextView, new ArrayList<String>());
        forecastView.setAdapter(forecastAdapter);

        forecastView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                String forecast = forecastAdapter.getItem(i);
                Intent intent = new Intent(getActivity(), DetailActivity.class);
                intent.putExtra(Intent.EXTRA_TEXT, forecast);
                startActivity(intent);
            }
        });

        return rootView;
    }

    public class FetchWeatherTask extends AsyncTask<String, Void, String[]>
    {

        private String getReadableString(long time)
        {
            Date date = new Date(time * 1000);
            SimpleDateFormat format = new SimpleDateFormat("E, MMM d");
            return format.format(date).toString();
        }

        private String formatHighsAndLows (double high, double low)
        {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            String unitType = preferences.getString(getString(R.string.pref_units_key), getString(R.string.pref_units_metric));

            if(unitType.equals(getString(R.string.pref_units_imperial)))
            {
                high = (high * 1.8) + 32;
                low = (low * 1.8) + 32;
            } else if(!unitType.equals(getString(R.string.pref_units_metric)))
            {
                Log.e(getTag(), "Unit not found.");
            }

            long roundedHigh = Math.round(high);
            long roundedLow = Math.round(low);

            String highLow = roundedHigh + "/" + roundedLow;
            return highLow;

        }

        private String[] getWeatherDataFromJSON(String JSON, int numberOfDays) throws JSONException
        {
            final String OWM_LIST = "list";
            final String OWM_WEATHER = "weather";
            final String OWM_TEMP = "temp";
            final String OWM_MAX = "max";
            final String OWM_MIN = "min";
            final String OWM_DATETIME = "dt";
            final String OWM_DESCRIPION = "main";

            JSONObject object = new JSONObject(JSON);
            JSONArray dataArray = object.getJSONArray(OWM_LIST);

            String[] result = new String[numberOfDays];
            for(int i = 0; i < dataArray.length(); i++)
            {
                String day;
                String description;
                String highAndLow;

                JSONObject weatherForecast = dataArray.getJSONObject(i);
                long dateTime = weatherForecast.getLong(OWM_DATETIME);
                day = getReadableString(dateTime);


                JSONObject weatherObject = weatherForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                description = weatherObject.getString(OWM_DESCRIPION);

                JSONObject temperatureObject = weatherForecast.getJSONObject(OWM_TEMP);
                double high = temperatureObject.getDouble(OWM_MAX);
                double low = temperatureObject.getDouble(OWM_MIN);

                highAndLow = formatHighsAndLows(high, low);
                result[i]  = day + " - " + description + " - " + highAndLow;

                for(String s : result)
                {
                    Log.v(this.getClass().getSimpleName(), "Forecast entry: " + s);
                }
            }

            return result;
        }



        @Override
        protected String[] doInBackground(String... pinCodes) {


            if(pinCodes.length == 0)
            {
                return null;
            }

            final int numberOfDays = 7;
            String postalCode = pinCodes[0];
            String mode = "json";
            String units = "metric";

            HttpURLConnection connection = null;
            BufferedReader reader = null;

            String forecastJson = null;

            try {

                //CONSTANTS
                final String QUERY_PARAM = "q";
                final String COUNT = "cnt";
                final String MODE = "mode";
                final String UNITS = "units";
                String BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";

                Uri builtUri = Uri.parse(BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, postalCode).appendQueryParameter(MODE, mode)
                                                  .appendQueryParameter(UNITS, units).appendQueryParameter(COUNT, Integer.toString(numberOfDays)).build();

                URL url = new URL(builtUri.toString());
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();

                InputStream stream = connection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if(stream == null)
                {
                    return null;
                }

                reader = new BufferedReader(new InputStreamReader(stream));
                String line;
                while((line = reader.readLine()) != null)
                {
                    buffer.append(line + "\n");
                }

                if(buffer.length() == 0)
                {
                    return null;
                }
                forecastJson = buffer.toString();

            } catch(IOException e) {
                e.printStackTrace();
            }
            finally {
                if(connection != null)
                {
                    connection.disconnect();
                }
                if(reader != null)
                {
                    try
                    {
                        reader.close();
                    } catch(final IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            }

            try {
                return getWeatherDataFromJSON(forecastJson, numberOfDays);
            } catch(JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String[] strings) {
            if(strings != null)
            {
                forecastAdapter.clear();
                for(String dayForecastStr : strings)
                {
                    forecastAdapter.add(dayForecastStr);
                }
            }
        }
    }

}




Java Source Code List

com.captainchloride.weather.ApplicationTest.java
com.captainchloride.weather.DetailActivity.java
com.captainchloride.weather.ForecastFragment.java
com.captainchloride.weather.MyActivity.java
com.captainchloride.weather.SettingsActivity.java