All Downloads are FREE. Search and download functionalities are using the official Maven repository.

it.tidalwave.bluebill.mobile.android.location.PickLocationActivity Maven / Gradle / Ivy

/***********************************************************************************************************************
 *
 * blueBill Mobile - open source birdwatching
 * ==========================================
 *
 * Copyright (C) 2009, 2010 by Tidalwave s.a.s. (http://www.tidalwave.it)
 * http://bluebill.tidalwave.it/mobile/
 *
 ***********************************************************************************************************************
 *
 * 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.
 *
 ***********************************************************************************************************************
 *
 * $Id: PickLocationActivity.java,v 97140ea1539e 2010/06/11 14:13:55 fabrizio $
 *
 **********************************************************************************************************************/
package it.tidalwave.bluebill.mobile.android.location;

import javax.annotation.Nonnull;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.openide.util.NbBundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.location.Address;
import android.location.LocationProvider;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import it.tidalwave.util.logging.Logger;
import it.tidalwave.util.NotFoundException;
import it.tidalwave.netbeans.util.Locator;
import it.tidalwave.geo.Coordinate;
import it.tidalwave.geo.Range;
import it.tidalwave.bluebill.observation.Location;
import it.tidalwave.bluebill.observation.Observation.Builder;
import it.tidalwave.bluebill.observation.simple.SimpleLocation;
import it.tidalwave.mobile.location.LocationFinder;
import it.tidalwave.mobile.location.LocationFinder.State;
import it.tidalwave.mobile.location.LocationPreferences;
import it.tidalwave.bluebill.mobile.observation.ObservationClipboard;
import it.tidalwave.bluebill.mobile.network.NetworkingPreferences;
import it.tidalwave.bluebill.mobile.android.preferences.BlueBillPreferenceActivity;
import it.tidalwave.bluebill.mobile.android.R;
import it.tidalwave.bluebill.mobile.android.about.AboutActivity;
import it.tidalwave.mobile.android.ui.AndroidUtilities;
import it.tidalwave.mobile.android.ui.ControlFlow;

/***********************************************************************************************************************
 *
 * This activity allows to ad a new Observation.
 * 
 * @author  Fabrizio Giudici
 * @version $Id: $
 *
 **********************************************************************************************************************/
public class PickLocationActivity extends Activity
  {
    private static final String CLASS = PickLocationActivity.class.getName();
    private static final Logger logger = Logger.getLogger(CLASS);

    @Nonnull
    private final LocationPreferences locationPreferences = Locator.find(LocationPreferences.class);
    
    @Nonnull
    private final NetworkingPreferences networkingPreferences = Locator.find(NetworkingPreferences.class);

    @Nonnull
    private final LocationFinder locationFinder = Locator.find(LocationFinder.class);

    private TextView tvState;

    private TextView tvProvider;

    private EditText etCoordinate;

    private EditText etPlace;

    private ImageButton btRecomputePlace;
    
    private ProgressBar pbProgress;

    private ImageView ivMap;

    private Map map = new HashMap();

    private Handler handler;

    private ControlFlow controlFlow;

    /*******************************************************************************************************************
     *
     *
     ******************************************************************************************************************/
    private final PropertyChangeListener locationFinderListener = new PropertyChangeListener()
      {
        public void propertyChange (final @Nonnull PropertyChangeEvent event)
          {
            handler.post(new Runnable()
              {
                public void run()
                  {
                    updateDisplay();
                  }
              });
          }
      };

    /*******************************************************************************************************************
     *
     *
     ******************************************************************************************************************/
    @Override
    protected void onCreate (final @Nonnull Bundle savedInstanceState)
      {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pick_location_activity);

        handler = new Handler();

        tvProvider = (TextView)findViewById(R.id.tvProvider);
        etCoordinate = (EditText)findViewById(R.id.etCoordinate);
        tvState = (TextView)findViewById(R.id.tvState);
        etPlace = (EditText)findViewById(R.id.etPlace);
        etPlace.requestFocus();

        final Button btOk = (Button)findViewById(R.id.btOk);
        btOk.setOnClickListener(new View.OnClickListener()
          {
            public void onClick (final @Nonnull View view)
              {
                commitLocation();
              }
          });

        btRecomputePlace = (ImageButton)findViewById(R.id.btRecomputePlace);
        pbProgress = (ProgressBar)findViewById(R.id.pbProgress);
        ivMap = (ImageView)findViewById(R.id.ivMap);

        pbProgress.setIndeterminate(true);
        btRecomputePlace.setEnabled(false);

        // FIXME: disable if the locationFinder is already working
        ((ImageButton)findViewById(R.id.btResamplePosition)).setOnClickListener(new View.OnClickListener()
          {
            public void onClick (final @Nonnull View view)
              {
                locationFinder.start();
              }
          });

        btRecomputePlace.setOnClickListener(new View.OnClickListener()
          {
            public void onClick (final @Nonnull View view)
              {
                locationFinder.findAddress();
              }
          });

        controlFlow = ControlFlow.forActivity(this);
      }

    /*******************************************************************************************************************
     *
     *
     ******************************************************************************************************************/
    @Override
    protected void onResume()
      {
        super.onResume();

        // here, so you can detect the locale change
        map.clear();
        map.put(State.COMPUTING_RANGE, NbBundle.getMessage(PickLocationActivity.class, "computingRange"));
        map.put(State.SEARCHING_FOR_ADDRESS, NbBundle.getMessage(PickLocationActivity.class, "placeSearchInProgress"));
        map.put(State.IDLE, "");

        final boolean geoCodingEnabled = locationFinder.isAddressSearchEnabled();
        findViewById(R.id.tvGeocodingDisabled).setVisibility(AndroidUtilities.visibility(!geoCodingEnabled));
        btRecomputePlace.setVisibility(AndroidUtilities.visibility(geoCodingEnabled));
//        btRecomputePlace.setEnabled(locationFinder.isAddressSearchEnabled());

        locationFinder.addPropertyChangeListener(locationFinderListener);
//        locationFinder.start(); // pre-started by ObservationsActivity
        updateDisplay();
      }

    /*******************************************************************************************************************
     *
     *
     ******************************************************************************************************************/
    @Override
    protected void onActivityResult (final int requestCode, final int resultCode, final @Nonnull Intent data)
      {
        setResult(resultCode, data);
        finish();
      }

    /*******************************************************************************************************************
     *
     *
     ******************************************************************************************************************/
    @Override
    protected void onPause()
      {
        super.onPause();
        locationFinder.removePropertyChangeListener(locationFinderListener);
        locationFinder.stop();

      }

    /*******************************************************************************************************************
     *
     *
     ******************************************************************************************************************/
    @Override
    public boolean onCreateOptionsMenu (final @Nonnull Menu menu)
      {
        final MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.preferences_options_menu, menu);
        return true;
      }

    /*******************************************************************************************************************
     *
     *
     ******************************************************************************************************************/
    @Override
    public boolean onOptionsItemSelected (final @Nonnull MenuItem item)
      {
        switch (item.getItemId())
          {
            case R.id.preferences:
                startActivity(new Intent(getBaseContext(), BlueBillPreferenceActivity.class));
                return true;

            case R.id.about:
                startActivity(new Intent(getBaseContext(), AboutActivity.class));
                return true;

            default:
                return super.onOptionsItemSelected(item);
          }
      }

    /*******************************************************************************************************************
     *
     *
     ******************************************************************************************************************/
    private void commitLocation()
      {
        final List capabilities = new ArrayList();

        try
          {
            capabilities.add(locationFinder.getRange());
          }
        catch (NotFoundException e)
          {
          }

        final Location location = new SimpleLocation(etPlace.getText().toString(), capabilities.toArray());
        final ObservationClipboard observationClipboard = Locator.find(ObservationClipboard.class);
        final Builder builder = observationClipboard.getBuilder();
        observationClipboard.setBuilder(builder.at(location));
        controlFlow.toNextStep();
      }

    /*******************************************************************************************************************
     *
     *
     ******************************************************************************************************************/
    private void updateDisplay()
      {
        try
          {
            final Range range = locationFinder.getRange();
            etCoordinate.setText(locationPreferences.format(range));
            btRecomputePlace.setEnabled(true);

            if (networkingPreferences.isNetworkConnectionAllowed())
              {
                showMap(range);
              }
          }
        catch (NotFoundException e)
          {
            etCoordinate.setText(NbBundle.getMessage(PickLocationActivity.class, "rangeNotAvailable"));
            btRecomputePlace.setEnabled(false);
          }
        
        final Address address = (Address)locationFinder.getAddress();

        if (address != null)
          {
            final StringBuilder buffer = new StringBuilder(address.getLocality());
//            final String featureName = address.getFeatureName();
//
//            if (featureName != null)
//              {
//                buffer.append(" (").append(featureName).append(")");
//              }
//            else
              {
                String separator = " (";
                String trailer = "";
                
                for (int line = 0; line < 1; line++)
                  {
                    final String addressLine = address.getAddressLine(line);

                    if (addressLine != null)
                      {
                        buffer.append(separator).append(addressLine);
                        separator = " ";
                        trailer = ")";
                      }
                  }

                buffer.append(trailer);
              }

            etPlace.setText(buffer.toString());
          }
        else
          {
            etPlace.setText(NbBundle.getMessage(PickLocationActivity.class, "unknownPlace"));
          }

        final State state = locationFinder.getState();

        if (state == State.IDLE)
          {
            tvState.setText("");
            tvProvider.setText("");
            pbProgress.setVisibility(View.INVISIBLE);
          }
        else
          {
            tvState.setText(map.get(state));
            pbProgress.setVisibility(View.VISIBLE);

            final StringBuilder buffer = new StringBuilder();
            final String providerName = locationFinder.getProviderName();
            buffer.append((providerName != null) ? providerName : "no provider");

            switch (locationFinder.getProviderStatus())
              {
                case LocationProvider.OUT_OF_SERVICE:
                  buffer.append(" is off");
                  break;

                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                  buffer.append(" is temporarily unavailable");
                  break;

                case LocationProvider.AVAILABLE:
                  buffer.append(" is on");
                  break;
              }

//            tvProvider.setText(buffer.toString());
            tvProvider.setText("");
          }
      }

    /*******************************************************************************************************************
     *
     *
     ******************************************************************************************************************/
    private void showMap (final @Nonnull Range range)
      {
        final Coordinate c = range.getCoordinate();
        final int zoom = 14;
        final int w = ivMap.getWidth();
        final int h = ivMap.getHeight();
        final String pattern = "http://maps.google.com/maps/api/staticmap?center=%1$f,%2$f&zoom=%3$d&size=%4$dx%5$d&sensor=false&" +
                                                                         "format=jpg&markers=color:blue|label:SS|%1$f,%2$f";
        final String url = String.format(Locale.ENGLISH, pattern, c.getLatitude(), c.getLongitude(), zoom, w, h);
        
        new Thread()
          {
            @Override
            public void run()
              {
                try
                  {
                    final Drawable image = AndroidUtilities.loadImage(url);
                    ivMap.post(new Runnable()
                      {
                        public void run()
                          {
                            logger.fine(">>>> calling setImageDrawable(%s)", image);
                            ivMap.setImageDrawable(image);
                          }
                      });
                  }
                catch (NotFoundException e)
                  {
                    logger.warning("Could not load map: %s", e.getMessage());
                  }
                catch (NullPointerException e) // defensive, see: BBMA-67
                  {
                    logger.warning("Could not load map: %s", e.getMessage());
                  }
              }
          }.start();
      }
  }