Android Open Source - arcgis-runtime-samples-android Main Activity






From Project

Back to project page arcgis-runtime-samples-android.

License

The source code is released under:

Apache License

If you think the Android project arcgis-runtime-samples-android 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

/* Copyright 2014 ESRI
 */*w  w  w  .j  a v  a 2 s  .  co m*/
 * All rights reserved under the copyright laws of the United States
 * and applicable international laws, treaties, and conventions.
 *
 * You may freely redistribute and use this sample code, with or
 * without modification, provided you include the original copyright
 * notice and use restrictions.
 *
 * See the Sample code usage restrictions document for further information.
 *
 */

package com.arcgis.android.samples.search.placesearch;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.MapView;
import com.esri.android.map.event.OnStatusChangedListener;
import com.esri.core.geometry.Envelope;
import com.esri.core.geometry.Point;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.SimpleMarkerSymbol;
import com.esri.core.symbol.TextSymbol;
import com.esri.core.tasks.geocode.Locator;
import com.esri.core.tasks.geocode.LocatorFindParameters;
import com.esri.core.tasks.geocode.LocatorGeocodeResult;

import java.util.List;


public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";

    MapView mMapView;
    EditText mSearchEditText;
    String mMapViewState;

    // Graphics layer to show geocode and reverse geocode results
    GraphicsLayer mLocationLayer;
    Point mLocationLayerPoint;
    String mLocationLayerPointString;

    // UI components
    static ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Setup and show progress dialog
        mProgressDialog = new ProgressDialog(this) {
            @Override
            public void onBackPressed() {
                // Back key pressed - just dismiss the dialog
                mProgressDialog.dismiss();
            }
        };

        // after the content of this activity is set
        // the map can be accessed from the layout
        mMapView = (MapView)findViewById(R.id.map);

        mLocationLayer = new GraphicsLayer();
        mMapView.addLayer(mLocationLayer);

        // set logo and enable wrap around
        mMapView.setEsriLogoVisible(true);
        mMapView.enableWrapAround(true);

        // Setup listener for map initialized
        mMapView.setOnStatusChangedListener(new OnStatusChangedListener() {

            @Override
            public void onStatusChanged(Object source, STATUS status) {
                if (source == mMapView && status == STATUS.INITIALIZED) {

                    if (mMapViewState == null) {
                        Log.i(TAG, "MapView.setOnStatusChangedListener() status=" + status.toString());
                    } else {
                        mMapView.restoreState(mMapViewState);
                    }

                }
            }
        });


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        // get a reference to the EditText widget for the search option
        View searchRef = menu.findItem(R.id.action_search).getActionView();
        mSearchEditText = (EditText) searchRef.findViewById(R.id.searchText);

        // set key listener to start search if Enter key is pressed
        mSearchEditText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if(keyCode == KeyEvent.KEYCODE_ENTER){
                    onSearchButtonClicked(mSearchEditText);
                    return true;
                }

                return false;
            }
        });

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_search) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Called from search_layout.xml when user presses Search button
     *
     * @param view
     */
    public void onSearchButtonClicked(View view){
        // Hide virtual keyboard
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

        // obtain address and execute locator task
        String address = mSearchEditText.getText().toString();
        executeLocatorTask(address);

    }

    /**
     * Set up the search parameters and execute the Locator task.
     *
     * @param address
     */
    private void executeLocatorTask(String address) {
        // Create Locator parameters from single line address string
        LocatorFindParameters findParams = new LocatorFindParameters(address);

        // Use the centre of the current map extent as the find location point
        findParams.setLocation(mMapView.getCenter(), mMapView.getSpatialReference());

        // Calculate distance for find operation
        Envelope mapExtent = new Envelope();
        mMapView.getExtent().queryEnvelope(mapExtent);
        // assume map is in metres, other units wont work, double current envelope
        double distance = (mapExtent != null && mapExtent.getWidth() > 0) ? mapExtent.getWidth() * 2 : 10000;
        findParams.setDistance(distance);
        findParams.setMaxLocations(2);

        // Set address spatial reference to match map
        findParams.setOutSR(mMapView.getSpatialReference());

        // Execute async task to find the address
        new LocatorAsyncTask().execute(findParams);
        mLocationLayerPointString = address;
    }

    /*
 * This class provides an AsyncTask that performs a geolocation request on a
 * background thread and displays the first result on the map on the UI
 * thread.
 */
    private class LocatorAsyncTask extends AsyncTask<LocatorFindParameters, Void, List<LocatorGeocodeResult>> {
        private Exception mException;

        public LocatorAsyncTask() {
        }

        @Override
        protected void onPreExecute() {
            // Display progress dialog on UI thread
            mProgressDialog.setMessage(getString(R.string.address_search));
            mProgressDialog.show();
        }

        @Override
        protected List<LocatorGeocodeResult> doInBackground(LocatorFindParameters... params) {
            // Perform routing request on background thread
            mException = null;
            List<LocatorGeocodeResult> results = null;

            // Create locator using default online geocoding service and tell it to
            // find the given address
            Locator locator = Locator.createOnlineLocator();
            try {
                results = locator.find(params[0]);
            } catch (Exception e) {
                mException = e;
            }
            return results;
        }

        @Override
        protected void onPostExecute(List<LocatorGeocodeResult> result) {
            // Display results on UI thread
            mProgressDialog.dismiss();
            if (mException != null) {
                Log.w(TAG, "LocatorSyncTask failed with:");
                mException.printStackTrace();
                Toast.makeText(MainActivity.this, getString(R.string.addressSearchFailed), Toast.LENGTH_LONG).show();
                return;
            }

            if (result.size() == 0) {
                Toast.makeText(MainActivity.this, getString(R.string.noResultsFound), Toast.LENGTH_LONG).show();
            } else {
                // Use first result in the list
                LocatorGeocodeResult geocodeResult = result.get(0);

                // get return geometry from geocode result
                Point resultPoint = geocodeResult.getLocation();
                // create marker symbol to represent location
                SimpleMarkerSymbol resultSymbol = new SimpleMarkerSymbol(Color.RED, 16, SimpleMarkerSymbol.STYLE.CROSS);
                // create graphic object for resulting location
                Graphic resultLocGraphic = new Graphic(resultPoint, resultSymbol);
                // add graphic to location layer
                mLocationLayer.addGraphic(resultLocGraphic);

                // create text symbol for return address
                String address = geocodeResult.getAddress();
                TextSymbol resultAddress = new TextSymbol(20, address, Color.BLACK);
                // create offset for text
                resultAddress.setOffsetX(-4 * address.length());
                resultAddress.setOffsetY(10);
                // create a graphic object for address text
                Graphic resultText = new Graphic(resultPoint, resultAddress);
                // add address text graphic to location graphics layer
                mLocationLayer.addGraphic(resultText);

                mLocationLayerPoint = resultPoint;

                // Zoom map to geocode result location
                mMapView.zoomToResolution(geocodeResult.getLocation(), 2);
            }
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();

        mMapViewState = mMapView.retainState();
        mMapView.pause();
    }

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

        // Start the MapView running again
        if (mMapView != null) {
            mMapView.unpause();
            if (mMapViewState != null) {
                mMapView.restoreState(mMapViewState);
            }
        }
    }

}




Java Source Code List

com.arcgis.android.samples.ExportTileCacheTask.ExportTileCacheTaskSampleActivity.java
com.arcgis.android.samples.cloudportal.featureservicetablequery.MainActivity.java
com.arcgis.android.samples.cloudportal.querycloudfeatureservice.MainActivity.java
com.arcgis.android.samples.dynamiclayer.DynamicLayerRendererActivity.java
com.arcgis.android.samples.geometrysample.BufferFragment.java
com.arcgis.android.samples.geometrysample.GeometrySampleActivity.java
com.arcgis.android.samples.geometrysample.GeometryUtil.java
com.arcgis.android.samples.geometrysample.SampleListFragment.java
com.arcgis.android.samples.geometrysample.SpatialRelationshipsFragment.java
com.arcgis.android.samples.geometrysample.UnionDifferenceFragment.java
com.arcgis.android.samples.localdata.localrasterdata.EditTextUtils.java
com.arcgis.android.samples.localdata.localrasterdata.FileBrowserFragment.java
com.arcgis.android.samples.localdata.localrasterdata.HillshadeRendererParametersFragment.java
com.arcgis.android.samples.localdata.localrasterdata.MainActivity.java
com.arcgis.android.samples.localdata.localrasterdata.OnDialogDismissListener.java
com.arcgis.android.samples.localdata.localrasterdata.RendererType.java
com.arcgis.android.samples.localdata.localrasterdata.StretchParametersFragment.java
com.arcgis.android.samples.maps.basemaps.MainActivity.java
com.arcgis.android.samples.maps.fragmentmanagement.BasemapListFragment.java
com.arcgis.android.samples.maps.fragmentmanagement.MainActivity.java
com.arcgis.android.samples.maps.fragmentmanagement.MapFragment.java
com.arcgis.android.samples.maps.helloworld.MainActivity.java
com.arcgis.android.samples.maps.maplegend.LegendDialogFragment.java
com.arcgis.android.samples.maps.maplegend.MainActivity.java
com.arcgis.android.samples.maps.maprotation.Compass.java
com.arcgis.android.samples.maps.maprotation.MainActivity.java
com.arcgis.android.samples.maps.switchmaps.MainActivity.java
com.arcgis.android.samples.maps.switchmaps.MapFragment.java
com.arcgis.android.samples.milsym2525c.MainActivity.java
com.arcgis.android.samples.milsym2525c.Mil2525cMessageParser.java
com.arcgis.android.samples.oauth2sample.MapFragment.java
com.arcgis.android.samples.oauth2sample.OAuth2Sample.java
com.arcgis.android.samples.oauth2sample.UserContentActivity.java
com.arcgis.android.samples.oauth2sample.UserContentArrayAdapter.java
com.arcgis.android.samples.oauth2sample.UserContentFragment.java
com.arcgis.android.samples.oauth2sample.UserWebmaps.java
com.arcgis.android.samples.search.placesearch.MainActivity.java
com.esri.android.sample.closestfacilities.MainActivity.java
com.esri.android.samples.mbtiles.LocalMBTiles.java
com.esri.android.samples.mbtiles.MBTilesLayer.java
com.esri.android.samples.mgrsgrid.LocateMGRSActivity.java
com.esri.arcgis.android.sample.runtimegeodb.CreateRuntimeGeodatabaseActivity.java
com.esri.arcgis.android.sample.simplemap.SimpleMapActivity.java
com.esri.arcgis.android.sample.simplemap.SimpleMapFragment.java
com.esri.arcgis.android.sample.simplemap.SingleFragmentActivity.java
com.esri.arcgis.android.samples.GeoJSONEarthquakeMap.GeoJSONEarthquakeMapActivity.java
com.esri.arcgis.android.samples.PopupUICustomization.LayerQueryTask.java
com.esri.arcgis.android.samples.PopupUICustomization.MyAttachmentsView.java
com.esri.arcgis.android.samples.PopupUICustomization.MyEditAttributesAdapter.java
com.esri.arcgis.android.samples.PopupUICustomization.MyMediaAdapter.java
com.esri.arcgis.android.samples.PopupUICustomization.MyMediaView.java
com.esri.arcgis.android.samples.PopupUICustomization.MyReadOnlyAttributesAdapter.java
com.esri.arcgis.android.samples.PopupUICustomization.MyTitleView.java
com.esri.arcgis.android.samples.PopupUICustomization.PopupFragment.java
com.esri.arcgis.android.samples.PopupUICustomization.PopupUICustomizationActivity.java
com.esri.arcgis.android.samples.addcsv2graphic.AddCSVActivity.java
com.esri.arcgis.android.samples.attributeeditor.AttributeEditorActivity.java
com.esri.arcgis.android.samples.attributeeditor.AttributeItem.java
com.esri.arcgis.android.samples.attributeeditor.AttributeListAdapter.java
com.esri.arcgis.android.samples.attributeeditor.FeatureLayerUtils.java
com.esri.arcgis.android.samples.basiclicense.MainActivity.java
com.esri.arcgis.android.samples.basiclicense.MessageDialogFragment.java
com.esri.arcgis.android.samples.classbreaksrenderer.ClassBreaksRendererActivity.java
com.esri.arcgis.android.samples.featuredusergroup.FeaturedGroupsActivity.java
com.esri.arcgis.android.samples.featuredusergroup.GroupsFragment.java
com.esri.arcgis.android.samples.featuredusergroup.ItemsFragment.java
com.esri.arcgis.android.samples.featuredusergroup.MapActivity.java
com.esri.arcgis.android.samples.geometryeditor.ConfirmDiscardDialogFragment.java
com.esri.arcgis.android.samples.geometryeditor.EditFailedDialogFragment.java
com.esri.arcgis.android.samples.geometryeditor.FeatureTypeData.java
com.esri.arcgis.android.samples.geometryeditor.FeatureTypeDialogFragment.java
com.esri.arcgis.android.samples.geometryeditor.GeometryEditorActivity.java
com.esri.arcgis.android.samples.identifytask.Identify.java
com.esri.arcgis.android.samples.measure.MainActivity.java
com.esri.arcgis.android.samples.nearby.Nearby.java
com.esri.arcgis.android.samples.offlineeditor.GDBUtil.java
com.esri.arcgis.android.samples.offlineeditor.OfflineActions.java
com.esri.arcgis.android.samples.offlineeditor.OfflineEditorActivity.java
com.esri.arcgis.android.samples.offlineeditor.TemplatePicker.java
com.esri.arcgis.android.samples.offlineroutingandgeocoding.RoutingAndGeocoding.java
com.esri.arcgis.android.samples.popupinwebmapforediting.PopupInWebmapForEditing.java
com.esri.arcgis.android.samples.popupinwebmapforviewing.PopupInWebmapForViewing.java
com.esri.arcgis.android.samples.querytask.MainActivity.java
com.esri.arcgis.android.samples.routing.MyAdapter.java
com.esri.arcgis.android.samples.routing.RoutingDialogFragment.java
com.esri.arcgis.android.samples.routing.RoutingListFragment.java
com.esri.arcgis.android.samples.routing.RoutingSample.java
com.esri.arcgis.android.samples.servicearea.EditFragment.java
com.esri.arcgis.android.samples.servicearea.ServiceAreaSample.java
com.esri.arcgis.android.samples.standardlicense.MainActivity.java
com.esri.arcgis.android.samples.standardlicense.MessageDialogFragment.java
com.esri.arcgis.android.samples.standardlicenseoffline.MainActivity.java
com.esri.arcgis.android.samples.standardlicenseoffline.MessageDialogFragment.java
com.esri.arcgis.android.samples.uniquevaluerenderer.UniqueValueRendererSampleActivity.java
com.esri.arcgis.android.samples.viewshed.Viewshed.java
com.esri.arcgis.android.samples.wmslayer.MainActivity.java
com.esri.arcgis.samples.offlineanalysis.MainActivity.java