com.handlerexploit.news.fragments.WeatherFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.handlerexploit.news.fragments.WeatherFragment.java

Source

/*
 *  Copyright (c) 2011 Daniel Huckaby
 *
 *  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.handlerexploit.news.fragments;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.handlerexploit.news.R;
import com.handlerexploit.news.data.WeatherProvider;
import com.handlerexploit.news.data.models.WeatherInfo;
import com.handlerexploit.news.data.models.WeatherInfo.Condition;
import com.handlerexploit.news.data.models.WeatherInfo.CurrentWeather;
import com.handlerexploit.news.widgets.RemoteImageView;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class WeatherFragment extends Fragment {

    private static ExecutorService threadPool = Executors.newSingleThreadExecutor();
    private static Handler handler = new Handler();

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

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

        final Activity activity = getActivity();
        if (activity != null) {
            threadPool.execute(new Runnable() {
                public void run() {
                    final SharedPreferences sharedPreferences = activity.getSharedPreferences(".preferences",
                            Context.MODE_PRIVATE);
                    String location = sharedPreferences.getString("Location", null);
                    if (location != null) {
                        final WeatherInfo weatherInfo = WeatherProvider.getWeather(location);
                        handler.post(new Runnable() {
                            public void run() {
                                render(weatherInfo);
                            }
                        });
                    } else {
                        Location lastKnownLocation = ((LocationManager) activity
                                .getSystemService(Context.LOCATION_SERVICE))
                                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (lastKnownLocation != null) {
                            double longitude = lastKnownLocation.getLongitude();
                            double latitude = lastKnownLocation.getLatitude();

                            String url = "http://maps.google.com/maps/geo?ll=" + latitude + "," + longitude;
                            try {
                                String response = EntityUtils
                                        .toString(new DefaultHttpClient().execute(new HttpGet(url)).getEntity());
                                JSONObject addressDetails = new JSONObject(response).getJSONArray("Placemark")
                                        .getJSONObject(0).getJSONObject("AddressDetails");
                                JSONObject locality = addressDetails.getJSONObject("Country")
                                        .getJSONObject("AdministrativeArea").getJSONObject("Locality");

                                String raw;
                                if (locality.get("PostalCode") == null) {
                                    raw = locality.getString("LocalityName");
                                } else {
                                    raw = locality.getJSONObject("PostalCode").getString("PostalCodeNumber");
                                }

                                sharedPreferences.edit().putString("Location", raw).commit();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (ParseException e) {
                                e.printStackTrace();
                            } catch (ClientProtocolException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            sharedPreferences.edit().putString("Location", "Miami").commit();
                        }

                        final WeatherInfo weatherInfo = WeatherProvider.getWeather("Miami");
                        if (weatherInfo != null) {
                            handler.post(new Runnable() {
                                public void run() {
                                    render(weatherInfo);
                                }
                            });
                        }
                    }
                }
            });
        }
    }

    private void render(WeatherInfo weatherInfo) {
        Activity activity = getActivity();
        if (activity != null && weatherInfo != null) {
            View root = getView();

            TextView city = (TextView) root.findViewById(R.id.city);
            city.setText(weatherInfo.getCity());

            CurrentWeather currentWeather = weatherInfo.getCurrentWeather();

            RemoteImageView icon = (RemoteImageView) root.findViewById(R.id.icon);
            int resId = activity.getResources().getIdentifier(currentWeather.getIcon(), "drawable",
                    activity.getPackageName());
            if (resId != 0) {
                ((ImageView) activity.findViewById(R.id.weather_small_logo)).setImageResource(resId);
                icon.setImageResource(resId);
            } else {
                ((ImageView) activity.findViewById(R.id.weather_small_logo)).setImageResource(R.drawable.unknown);
                icon.setImageResource(R.drawable.unknown);
            }

            TextView temp = (TextView) root.findViewById(R.id.temp);
            temp.setText(currentWeather.getTempF() + " \u00B0F | " + currentWeather.getTempC() + " \u00B0C");
            ((TextView) activity.findViewById(R.id.weather_small_text))
                    .setText(currentWeather.getTempF() + "\u00B0");

            TextView condition = (TextView) root.findViewById(R.id.condition);
            String conditionText = currentWeather.getCondition();
            if (conditionText != null && !conditionText.equals("")) {
                condition.setText(conditionText);
            } else {
                condition.setText("N/A");
            }

            TextView windCondition = (TextView) root.findViewById(R.id.windCondition);
            windCondition.setText(currentWeather.getWindCondition());

            TextView humidity = (TextView) root.findViewById(R.id.humidity);
            humidity.setText(currentWeather.getHumidity());

            LinearLayout forcastConditions = (LinearLayout) root.findViewById(R.id.forcastConditions);
            forcastConditions.removeAllViews();

            LayoutInflater inflater = LayoutInflater.from(activity);
            LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
            params.weight = 1f;

            ArrayList<Condition> forcastArray = weatherInfo.getForcastConditions();
            for (int i = 0; i < forcastArray.size(); i++) {
                Condition forcastCondition = forcastArray.get(i);
                View forcastRoot = inflater.inflate(R.layout.fragment_weather_condition_item, null);

                TextView forcastDay = (TextView) forcastRoot.findViewById(R.id.day);
                forcastDay.setText(forcastCondition.getDay());

                RemoteImageView forcastIcon = (RemoteImageView) forcastRoot.findViewById(R.id.icon);
                int forcastResId = activity.getResources().getIdentifier(forcastCondition.getIcon(), "drawable",
                        activity.getPackageName());
                if (forcastResId != 0) {
                    forcastIcon.setImageResource(forcastResId);
                } else {
                    forcastIcon.setImageResource(R.drawable.unknown);
                }

                TextView forcastHigh = (TextView) forcastRoot.findViewById(R.id.high);
                forcastHigh.setText(forcastCondition.getHigh() + "\u00B0");

                TextView forcastLow = (TextView) forcastRoot.findViewById(R.id.low);
                forcastLow.setText(forcastCondition.getLow() + "\u00B0");

                forcastConditions.addView(forcastRoot, params);
            }
        }
    }
}