joshuatee.wx.LocationFragment.java Source code

Java tutorial

Introduction

Here is the source code for joshuatee.wx.LocationFragment.java

Source

/*
    
Copyright 2013, 2014 joshua.tee@gmail.com
    
This file is part of wX.
    
wX is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
wX is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with wX.  If not, see <http://www.gnu.org/licenses/>.
    
 */

package joshuatee.wx;

import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import joshuatee.wx.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.LayerDrawable;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.support.v4.app.Fragment;

public class LocationFragment extends Fragment implements OnItemSelectedListener, OnClickListener {

    Spinner spinner1;
    int loc_num_int_current;

    int refresh_loc_min_current;
    long last_refresh = (long) 0;

    String x = "";
    String y = "";
    String loc_num = "";
    String rid1 = "";

    String alert_cod_radar_current = "";

    String seven_day_ext = "";
    String seven_day_sum = "";

    String hazards_ext = "";
    String hazards_sum = "";
    String hazards_url = "";

    int current_loc = -1;

    boolean seven_day_ext_shown = false;
    boolean hazards_shown = false;
    boolean image_expanded = false;

    DisplayMetrics dm;

    String[] current_str;
    String loc_display_img_current;

    int highlight_color = Color.YELLOW;
    int background_color = Color.WHITE;
    String highlight_color_str = "yellow";
    String background_color_str = "white";

    SharedPreferences preferences;
    SharedPreferences.Editor editor;

    View view;

    String cur_loc = "";
    final String add_loc_str = "Add Location...";
    String simple_mode_current = "";
    TextView tv_sunrise;

    Resources res;
    String hazard_raw = "";

    TouchImageView2 img;
    final float init_zoom = 1.50f;
    final float max_zoom = 6.0f; // was 4

    int i = 0;

    String x_old = "";
    String y_old = "";

    long current_time;
    long current_time_sec;
    long refresh_interval_sec;

    LayerDrawable ld1;
    ArrayAdapter<String> dataAdapter;

    String[] loc_str_arr;

    Button button_cur;
    TextView tv_stat;
    TextView button_for;
    TextView tv_hazard;

    String cur_str = "";
    String site_str = "";

    String t1 = "";
    String t2 = "";

    Intent intent;

    Pattern p;
    Matcher m;

    String newline;

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

        view = inflater.inflate(R.layout.fragment_location, container, false);

        if (preferences.getString("THEME_BLUE", "").contains("white")) {
            highlight_color = Color.BLUE;
            background_color = Color.BLACK;
            highlight_color_str = "blue";
            background_color_str = "black";
        }

        img = (TouchImageView2) view.findViewById(R.id.iv_1);
        img.setMaxZoom(max_zoom);

        View v_cur = view.findViewById(R.id.current_generic);
        v_cur.setOnClickListener(this);
        View v_cur_4 = view.findViewById(R.id.forecast_generic_status);
        v_cur_4.setOnClickListener(this);
        registerForContextMenu(v_cur_4);

        View v_forecast = view.findViewById(R.id.forecast_generic);
        v_forecast.setOnClickListener(this);
        View v_hazard = view.findViewById(R.id.hazards_generic);
        v_hazard.setOnClickListener(this);
        TextView tv_haz = (TextView) v_hazard.findViewById(R.id.hazards_generic);
        tv_haz.setTextColor(highlight_color);

        tv_sunrise = (TextView) view.findViewById(R.id.tv_sunrise);
        tv_sunrise.setVisibility(View.GONE);

        spinner1 = (Spinner) view.findViewById(R.id.spinner1);

        loc_num_int_current = preferences.getInt("LOC_NUM_INT", -1);
        simple_mode_current = preferences.getString("SIMPLE_MODE", "");

        loc_str_arr = new String[loc_num_int_current + 1];
        for (i = 0; i < loc_num_int_current; i++) {
            loc_str_arr[i] = preferences.getString("LOC" + Integer.toString(i + 1) + "_LABEL", "");
        }
        loc_str_arr[loc_num_int_current] = add_loc_str;

        dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, loc_str_arr);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner1.setAdapter(dataAdapter);
        spinner1.setOnItemSelectedListener(this);

        // comment out the following if loc1 desired at startup

        //int cur_loc_int = Integer.parseInt(cur_loc);
        //current_loc = cur_loc_int-1;

        current_loc = Integer.parseInt(cur_loc) - 1;
        spinner1.setSelection(current_loc);

        if (alert_cod_radar_current.contains("WX") && Utility.US(x)) {
            img.setZoom(init_zoom);
            img.setMinZoom(init_zoom);
        }

        // FIXME, remove the views above and consolidate

        button_cur = (Button) view.findViewById(R.id.current_generic);
        tv_stat = (TextView) view.findViewById(R.id.forecast_generic_status);
        button_for = (TextView) view.findViewById(R.id.forecast_generic);
        tv_hazard = (TextView) view.findViewById(R.id.hazards_generic);

        return view;
    }

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

        dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);

        res = this.getResources();
        newline = System.getProperty("line.separator");

        // uncomment the following if loc1 is desired at startup
        //loc_num = "1";

        preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        editor = preferences.edit();

        // comment out the following two lines if loc1 is desired at startup
        cur_loc = preferences.getString("CURRENT_LOC_FRAGMENT", "1");
        loc_num = cur_loc;
        refresh_loc_min_current = preferences.getInt("REFRESH_LOC_MIN", 30);
        loc_display_img_current = preferences.getString("LOC_DISPLAY_IMG", "");
        alert_cod_radar_current = preferences.getString("ALERT_COD_RADAR", "");
        x = preferences.getString("LOC" + cur_loc + "_X", ""); // fix for init zoom of non-US

    }

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

        //int loc_num_int_current = preferences.getInt("LOC_NUM_INT",-1);

        loc_num_int_current = preferences.getInt("LOC_NUM_INT", -1);

        //int loc_num2 = pos + 1;

        //String loc_str = Integer.toString(loc_num2);

        if (current_loc != pos) {

            if (pos != loc_num_int_current) {

                current_loc = pos;

                loc_num = Integer.toString(pos + 1);
                editor.putString("CURRENT_LOC_FRAGMENT", loc_num);
                editor.commit();

                x = preferences.getString("LOC" + loc_num + "_X", "");
                y = preferences.getString("LOC" + loc_num + "_Y", "");

                loc_display_img_current = preferences.getString("LOC_DISPLAY_IMG", "");

                if (alert_cod_radar_current.contains("WX") && Utility.US(x))
                    img.setZoom(init_zoom);
                else
                    img.setZoom(1.0f);

                refresh_dynamic_content();

            } else {

                intent = new Intent(getActivity(), SettingsLocationGenericActivity.class);
                intent.putExtra(SettingsLocationGenericActivity.LOC_NUM, Integer.toString(pos + 1));
                startActivity(intent);
                spinner1.setSelection(current_loc);

            }
        } // end check if current loc is pos

    }

    public void onNothingSelected(AdapterView<?> parent) {
    }

    public void refresh_dynamic_content() {

        tv_sunrise.setText("");
        tv_sunrise.setVisibility(View.GONE);
        seven_day_ext_shown = false;

        new GetForecast().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

        if (loc_display_img_current.startsWith("t") && simple_mode_current.startsWith("f")) {
            new GetRadar().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }

        long current_time = System.currentTimeMillis();
        last_refresh = current_time / 1000;

        editor.putLong("LOC_LAST_UPDATE", last_refresh);
        editor.commit();

    }

    public void onResume() {

        loc_num_int_current = preferences.getInt("LOC_NUM_INT", -1);
        refresh_loc_min_current = preferences.getInt("REFRESH_LOC_MIN", 30);
        last_refresh = preferences.getLong("LOC_LAST_UPDATE", 0);

        loc_str_arr = new String[loc_num_int_current + 1];
        for (i = 0; i < loc_num_int_current; i++) {
            loc_str_arr[i] = preferences.getString("LOC" + Integer.toString(i + 1) + "_LABEL", "");
        }
        loc_str_arr[loc_num_int_current] = add_loc_str;

        dataAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, loc_str_arr);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // fix for 2 or more loc deleted
        cur_loc = preferences.getString("CURRENT_LOC_FRAGMENT", "1");
        current_loc = Integer.parseInt(cur_loc) - 1;

        spinner1.setAdapter(dataAdapter);
        spinner1.setSelection(current_loc);
        spinner1.setOnItemSelectedListener(this);

        current_time = System.currentTimeMillis();
        current_time_sec = current_time / 1000;
        refresh_interval_sec = refresh_loc_min_current * 60;

        x_old = x;
        y_old = y;

        loc_num = cur_loc;

        x = preferences.getString("LOC" + loc_num + "_X", "");
        y = preferences.getString("LOC" + loc_num + "_Y", "");

        loc_display_img_current = preferences.getString("LOC_DISPLAY_IMG", "");

        if (!(refresh_loc_min_current == 0)) {
            if (current_time_sec > (last_refresh + refresh_interval_sec) || !x.equals(x_old) || !y.equals(y_old)) {
                refresh_dynamic_content();
            }
        }

        super.onResume();

    }

    @Override
    public void onClick(View v2) {
        switch (v2.getId()) {

        case R.id.forecast_generic_status:
            refresh_dynamic_content();
            break;

        case R.id.current_generic:
            intent = new Intent(getActivity(), SPCSoundingsActivity.class);
            intent.putExtra(SPCSoundingsActivity.URL,
                    new String[] { preferences.getString("NWS" + loc_num, ""), "" });
            startActivity(intent);
            break;

        case R.id.forecast_generic:
            if (seven_day_ext_shown) {
                button_for.setText(seven_day_sum);
                seven_day_ext_shown = false;
                tv_sunrise.setText("");
                tv_sunrise.setVisibility(View.GONE);
            } else {
                tv_sunrise.setVisibility(View.VISIBLE);
                if (Utility.US(x)) {
                    new GetSunrise().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
                button_for.setText(seven_day_ext);
                seven_day_ext_shown = true;
            }
            break;

        case R.id.hazards_generic:
            if (hazards_shown) {
                tv_hazard.setTextColor(highlight_color);
                tv_hazard.setText(Html.fromHtml(hazards_sum));
                hazards_shown = false;
            } else {
                GetHazards();
                hazards_shown = true;
            }
            break;

        }

    }

    private class GetRadar extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {

            rid1 = Utility.GetRid(preferences, loc_num);
            alert_cod_radar_current = preferences.getString("ALERT_COD_RADAR", "");

            if (Utility.US(x)) {

                ld1 = UtilityUSImg.GetPreferredLayeredImg(getActivity(), rid1, "ref");

            } else if (x.contains("CANADA")) {
                ld1 = UtilityCanadaImg.GetRadarBitmapOptionsApplied(getActivity(), rid1, "");
            } else if (x.contains("AUSTRALIA")) {
                ld1 = UtilityAustraliaImg.GetRadarBitmapOptionsApplied(getActivity(), rid1 + "3", "");

            } else if (x.contains("NZ")) {
                ld1 = UtilityNZImg.GetRadarBitmapOptionsApplied(getActivity(), rid1);
            }

            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

            if (Utility.US(x)) {
                UtilityImg.ResizeViewSetLD(dm, ld1, img);
            }
            // both CA and AU
            else {
                UtilityImg.ResizeViewSetLD(dm, ld1, img);

            }

        }

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected void onProgressUpdate(String... values) {
        }
    }

    void GetHazards() {
        if (!x.contains("CANADA") && !x.contains("AUSTRALIA")) {
            hazards_ext = Utility.GetHazards(hazard_raw);
            hazards_ext = hazards_ext.replace("<hr /><br />", "");
        } else {
            hazards_ext = hazard_raw;
        }

        tv_hazard.setText(Html.fromHtml(hazards_ext));
        tv_hazard.setTextColor(background_color);

    }

    private class GetForecast extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {

            seven_day_ext = "";
            seven_day_sum = "";
            hazards_sum = "";
            hazards_url = "";
            try {
                current_str = Utility.GetCurrentConditionsV2(getActivity(), x, y);
                cur_str = current_str[0];
                site_str = current_str[1];
                seven_day_ext = current_str[3];
                seven_day_sum = current_str[2];
                hazards_sum = current_str[4];
                hazards_url = current_str[5];

                if (!x.contains("CANADA")) {
                    hazard_raw = Utility.GetStringFromURLSep(hazards_url);
                } else {
                    hazard_raw = UtilityCanada.GetHazardsFromURL(hazards_url);
                }

            } catch (Exception e) {

            }

            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

            button_cur.setText(cur_str);
            tv_stat.setText(site_str);
            button_for.setText(seven_day_sum);

            if (!x.contains("CANADA")) {
                String hazard_sum_async = "";
                try {
                    p = Pattern.compile("<h3>(.*?)</h3>");
                    m = p.matcher(hazard_raw);
                    while (m.find()) {
                        hazard_sum_async = hazard_sum_async + newline + m.group(1);
                    }

                } catch (Exception e) {
                }
                hazard_sum_async = hazard_sum_async.replaceAll("^" + newline, "");

                if (hazard_sum_async.equals("")) {
                    tv_hazard.setVisibility(View.GONE);
                } else {
                    hazard_sum_async = hazard_sum_async.replace(newline, "<br>");
                    hazard_sum_async = "<font color=" + highlight_color_str + ">"
                            + hazard_sum_async.toUpperCase(Locale.US) + "</font>";

                    tv_hazard.setText(Html.fromHtml(hazard_sum_async));
                    tv_hazard.setVisibility(View.VISIBLE);
                }
                hazards_sum = hazard_sum_async;
            } else {
                if (hazards_sum.equals("")) {
                    tv_hazard.setVisibility(View.GONE);
                } else {
                    hazards_sum = "<font color=" + highlight_color_str + ">" + hazards_sum.toUpperCase(Locale.US)
                            + "</font>";
                    tv_hazard.setText(Html.fromHtml(hazards_sum));
                    tv_hazard.setVisibility(View.VISIBLE);
                }
            }

            if (getActivity() != null) {
                getActivity().setProgressBarIndeterminateVisibility(false);
            }

        }

        @Override
        protected void onPreExecute() {
            if (getActivity() != null) {
                getActivity().setProgressBarIndeterminateVisibility(true);
            }

        }

        @Override
        protected void onProgressUpdate(String... values) {
        }
    }

    private class GetSunrise extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {

            try {
                String sunrise_url = "http://www.wunderground.com/cgi-bin/findweather/hdfForecast?query="
                        + preferences.getString("ZIPCODE" + loc_num, "");
                String dataAsString = Utility.GetStringFromURL(sunrise_url);
                p = Pattern.compile(
                        "id=.cc-sun-rise.>([0-9]{1,2}:[0-9][0-9])</span>.*cc-sun-set.>([0-9]{1,2}:[0-9][0-9])</span>.*");
                m = p.matcher(dataAsString);
                t1 = "";
                t2 = "";
                while (m.find()) {
                    t1 = m.group(1);
                    t2 = m.group(2);
                }

            } catch (Exception e) {
            }

            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

            tv_sunrise.setText("Sunrise: " + t1 + "am   " + "Sunset: " + t2 + "pm");

        }

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected void onProgressUpdate(String... values) {
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

        switch (v.getId()) {
        case R.id.forecast_generic_status:
            menu.add(0, v.getId(), 0, "Edit Location..");
            break;
        }

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        if (getUserVisibleHint()) {
            if (item.getItemId() == R.id.forecast_generic_status) {
                intent = new Intent(getActivity(), SettingsLocationGenericActivity.class);
                intent.putExtra(SettingsLocationGenericActivity.LOC_NUM, loc_num);
                startActivity(intent);
            }
            return true;
        } else {
            return false;
        }
    }

}