本文介绍了Android的谷歌地图:尝试使用locationClient的片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换为locationClient给出的谷歌开发者页面从FragmentActivity到碎片的code。我似乎在我的onCreateView将得到一个空指针异常的地方我得到的句柄的TextView mLatLng =(TextView中)getView()findViewById(R.id.lat_lng);

 公共类最热门的扩展片段工具
        LocationListener的,
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {

    //请求连接到位置服务
    私人LocationRequest mLocationRequest;

    //保存执行位置客户端的当前实例中该对象
    私人LocationClient mLocationClient;

    //句柄到UI部件
    私人TextView的mLatLng;
    私人TextView的mAddress;
    私人进度mActivityIndi​​cator;
    私人TextView的mConnectionState;
    私人TextView的mConnectionStatus;

    //处理为共享preferences这个应用程序
    共享preferences米preFS;

    //处理到共享preferences编辑器
    共享preferences.Editor mEditor;

    / *
     *请注意,如果更新已开启。开始时是假;被设置为真,在
     * LocationUpdateReceiver的方法handleRequestSuccess。
     *
     * /
    布尔mUpdatesRequested = FALSE;

    / *
     *初始化活动
     * /
    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
            捆绑savedInstanceState){
        Log.d(onCreatView,内部onCreatView);

        查看rootView = inflater.inflate(R.layout.hottest,集装箱,假);
     //获取句柄到用户界面视图对象
        mLatLng =(TextView中)getView()findViewById(R.id.lat_lng)。
        mAddress =(TextView中)getView()findViewById(R.id.address)。
        mActivityIndi​​cator =(进度)getView()findViewById(R.id.address_progress)。
        mConnectionState =(TextView中)getView()findViewById(R.id.text_connection_state)。
        mConnectionStatus =(TextView中)getView()findViewById(R.id.text_connection_status)。

        //创建一个新的全球定位参数对象
        mLocationRequest = LocationRequest.create();

        / *
         *设置的更新间隔
         * /
        mLocationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);

        //使用高精度
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        //区间上限设置为一分钟
        mLocationRequest.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);

        //注意位置更新关闭,直到用户打开他们
        mUpdatesRequested = FALSE;

        //打开共享preferences
        :M preFS = getActivity()getShared preferences(LocationUtils.SHARED_ preFERENCES,Context.MODE_PRIVATE);

        //获取一个编辑器
        mEditor = M prefs.edit();

        / *
         *创建一个新的位置客户端,使用封闭类
         *手柄回调。
         * /
        mLocationClient =新LocationClient(getActivity(),这一点,这一点);

        返回rootView;
    }

    / *
     *当活动不再是可见的所有调用。
     *停止更新和断开连接。
     * /
    @覆盖
    公共无效的onStop(){

        //如果客户端连接
        如果(mLocationClient.isConnected()){
            stopPeriodicUpdates();
        }

        //断开连接后()被调用时,客户端被认为是死的。
        mLocationClient.disconnect();

        super.onStop();
    }
    / *
     *当活动即将进入后台调用。
     *用户界面的某些部分可能是可见的,但活动是无效的。
     * /
    @覆盖
    公共无效的onPause(){

        //保存当前设置更新
        mEditor.putBoolean(LocationUtils.KEY_UPDATES_REQUESTED,mUpdatesRequested);
        mEditor.commit();

        super.onPause();
    }

    / *
     *当调用的活动重新启动时,它变得明显之前。
     * /
    @覆盖
    公共无效的OnStart(){

        super.onStart();

        / *
         *连接的客户端。不要重新启动任何请求在这里;
         *代替,等待onResume()
         * /
        mLocationClient.connect();

    }
    / *
     *系统检测到这种活动现在是可见时调用。
     * /
    @覆盖
    公共无效onResume(){
        super.onResume();

        //如果应用程序已经为获得位置更新设置,得到它
        如果(M prefs.contains(LocationUtils.KEY_UPDATES_REQUESTED)){
            mUpdatesRequested = M prefs.getBoolean(LocationUtils.KEY_UPDATES_REQUESTED,假);

        //否则,关闭位置更新,直到请求
        } 其他 {
            mEditor.putBoolean(LocationUtils.KEY_UPDATES_REQUESTED,假);
            mEditor.commit();
        }

    }

    / *
     *手柄结果返回到该活动由其他活动开始
     * startActivityForResult()。特别是,该方法onConnectionFailed()中
     * LocationUpdateRemover和LocationUpdateRequester可致电startResolutionForResult()来
     *开始处理谷歌Play业务问题的活动。这样做的结果
     *调用返回这里,以onActivityResult。
     * /
    @覆盖
    公共无效onActivityResult(INT申请code,INT结果code,意图意图){
        super.onActivityResult(要求code,因此code,意图);
        为(片段片段:getActivity()getSupportFragmentManager()getFragments()){
            fragment.onActivityResult(要求code,因此code,意图);
        }
        //选择什么根据请求code做
        开关(要求code){

            //如果请求code匹配的onConnectionFailed发送的code
            案例LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST:

                开关(结果code){
                    //如果谷歌Play业务解决了这个问题
                    案例Activity.RESULT_OK:

                        //日志结果
                        Log.d(LocationUtils.APPTAG,的getString(R.string.resolved));

                        //显示结果
                        mConnectionState.setText(R.string.connected);
                        mConnectionStatus.setText(R.string.resolved);
                    打破;

                    //如果任何其他的结果是由谷歌返回播放服务
                    默认:
                        //日志结果
                        Log.d(LocationUtils.APPTAG,的getString(R.string.no_resolution));

                        //显示结果
                        mConnectionState.setText(R.string.disconnected);
                        mConnectionStatus.setText(R.string.no_resolution);

                    打破;
                }

            //如果收到任何其他请求code
            默认:
               //报告,本次活动接收到未知的请求,code
               Log.d(LocationUtils.APPTAG,
                       的getString(R.string.unknown_activity_request_ code,请求code));

               打破;
        }
    }

    / **
     *验证可发出请求之前,谷歌播放服务。
     *
     * @返回如果谷歌Play业务真正可用,否则为false
     * /
    私人布尔servicesConnected(){

        //检查谷歌Play业务是提供
        INT结果code =
                GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());

        //如果谷歌Play业务是提供
        如果(ConnectionResult.SUCCESS ==结果code){
            //在调试模式下,登录状态
            Log.d(LocationUtils.APPTAG,的getString(R.string.play_services_available));

            // 继续
            返回true;
        //谷歌Play业务是不适合某些原因
        } 其他 {
            //显示一个错误对话框
            对话对话框= GooglePlayServicesUtil.getErrorDialog(结果code,getActivity(),0);
            如果(对话!= NULL){
                ErrorDialogFragment errorFragment =新ErrorDialogFragment();
                errorFragment.setDialog(对话);
                errorFragment.show(getActivity()getSupportFragmentManager(),LocationUtils.APPTAG);
            }
            返回false;
        }
    }

    / **
     *通过获取位置按钮时调用。
     *
     *来电getLastLocation()获取当前位置
     *
     * @参数V配合此方法相关联,在这种情况下,一个按钮的视图对象。
     * /
    公共无效的getLocation(视图v){

        //如果谷歌播放服务提供
        如果(servicesConnected()){

            //获取当前位置
            位置currentLocation = mLocationClient.getLastLocation();

            //在UI中显示的当前位置
            mLatLng.setText(LocationUtils.getLatLng(getActivity(),currentLocation));
        }
    }

    / **
     *通过获取地址按钮时调用。
     *获取的当前位置的地址,使用反向地理编码。这仅适用于当
     *地理编码服务。
     *
     * @参数V配合此方法相关联,在这种情况下,一个按钮的视图对象。
     * /
    //对于Eclipse ADT有大约地理coder.is present燮preSS警告()
    @燮pressLint(NewApi)
    公共无效的getAddress(视图v){

        //在姜饼和更高版本,使用地理coder.is present(),看是否有地缘codeR可用。
        如果(Build.VERSION.SDK_INT> = Build.VERSION_ codeS.GINGERBREAD和放大器;&安培;!地理coder.is present()){
            //没有地理codeR为present。发出错误信息
            Toast.makeText(getActivity(),R.string.no_geo coder_available,Toast.LENGTH_LONG).show();
            返回;
        }

        如果(servicesConnected()){

            //获取当前位置
            位置currentLocation = mLocationClient.getLastLocation();

            //开启无限期活动指示灯
            mActivityIndi​​cator.setVisibility(View.VISIBLE);

            //启动后台任务
            (新Hottest.GetAddressTask(getActivity()))执行(currentLocation);
        }
    }

    / **
     *通过调用开始更新按钮
     *发送请求到开始位置更新
     *
     * @参数V配合此方法相关联,在这种情况下,一个按钮的视图对象。
     * /
    公共无效startUpdates(视图v){
        mUpdatesRequested = TRUE;

        如果(servicesConnected()){
            startPeriodicUpdates();
        }
    }

    / **
     *通过调用停止更新按钮
     *发送请求删除位置更新
     *提出要求。
     *
     * @参数V配合此方法相关联,在这种情况下,一个按钮的视图对象。
     * /
    公共无效stopUpdates(视图v){
        mUpdatesRequested = FALSE;

        如果(servicesConnected()){
            stopPeriodicUpdates();
        }
    }

    / *
     *通过调用定位服务时,请求连接
     *客户成功完成。在这一点上,你可以
     *请求当前位置或启动周期性更新
     * /
    @覆盖
    公共无效onConnected(束捆){
        mConnectionStatus.setText(R.string.connected);

        如果(mUpdatesRequested){
            startPeriodicUpdates();
        }
    }

    / *
     *通过调用定位服务如果连接到
     *位置客户端下降,因为错误的。
     * /
    @覆盖
    公共无效onDisconnected(){
        mConnectionStatus.setText(R.string.disconnected);
    }

    / *
     *通过调用定位服务如果尝试
     *定位服务失败。
     * /
    @覆盖
    公共无效onConnectionFailed(ConnectionResult connectionResult){

        / *
         *谷歌播放服务可以解决一些错误检测。
         *如果错误的分辨率,尝试发送一个意向
         *启动谷歌播放服务活动,可以解决
         * 错误。
         * /
        如果(connectionResult.hasResolution()){
            尝试 {

                //开始的,试图解决错误的活动
                connectionResult.startResolutionForResult(
                        getActivity(),
                        LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);

                / *
                *抛出,如果谷歌Play业务取消了原有的
                * PendingIntent
                * /

            }赶上(IntentSender.SendIntentException E){

                //记录错误
                e.printStackTrace();
            }
        } 其他 {

            //如果没有解决可用,显示与错误的用户对话框。
            showErrorDialog(connectionResult.getError code());
        }
    }

    / **
     *报告位置更新到用户界面。
     *
     *参数的位置更新的位置。
     * /
    @覆盖
    公共无效onLocationChanged(位置定位){

        //报告,该位置已更新的用户界面
        mConnectionStatus.setText(R.string.location_updated);

        //在用户界面,设置经度和纬度收到的价值
        mLatLng.setText(LocationUtils.getLatLng(getActivity(),位置));
    }

    / **
     *在响应于一个请求以开始更新,发送请求
     *以位置服务
     * /
    私人无效startPeriodicUpdates(){

        mLocationClient.requestLocationUpdates(mLocationRequest,这一点);
        mConnectionState.setText(R.string.location_requested);
    }

    / **
     *在响应于请求来停止更新,将请求发送到
     * 位置服务
     * /
    私人无效stopPeriodicUpdates(){
        mLocationClient.removeLocationUpdates(本);
        mConnectionState.setText(R.string.location_updates_stopped);
    }

    / **
     *调用getFromLocation()在后台AsyncTask的。
     *类使用下列通用类型:
     *位置 -  {@link android.location.Location}包含对象的当前位置,
     *通过作为输入参数来doInBackground()
     *虚空 - 指示进度的单位不使用该子类
     * String  - 传递给onPostExecute的地址()
     * /
    保护类GetAddressTask扩展的AsyncTask<位置,太虚,字符串> {

        //存储传递给AsyncTask的情况下,当系统实例化。
        语境localContext;

        //构造函数由系统调用来实例化任务
        公共GetAddressTask(上下文的背景下){

            //必选的AsyncTask的语义
            超();

            //设置上下文的后台任务
            localContext =背景;
        }

        / **
         *获取地理编码服务实例,通过纬度和经度,格式化返回
         *地址,并返回地址到UI线程。
         * /
        @覆盖
        保护字符串doInBackground(位置... PARAMS){
            / *
             *获取一个新的地理编码服务的实例,为局部地址设置。本例中使用
             * android.location.Geo codeR,但符合标准的解决其他地理codeRS
             *也可以使用。
             * /
            地理codeR地理codeR =新的地缘codeR(localContext,Locale.getDefault());

            //从输入参数列表获取当前位置
            位置位置= PARAMS [0];

            //创建一个列表,包含结果地址
            名单<地址>地址= NULL;

            //尝试获得一个地址为当前位置。抓住IO或网络问题。
            尝试 {

                / *
                 *调用同步getFromLocation()方法的纬度和
                 *在当前位置的经度。返回至多地址。
                 * /
                地址=地理coder.getFromLocation(location.getLatitude()
                    location.getLongitude(),1-
                );

                //捕捉网络或其他I / O问题。
                }赶上(IOException异常exception1){

                    //记录错误,并返回一个错误信息
                    Log.e(LocationUtils.APPTAG,的getString(R.string.IO_Exception_getFromLocation));

                    //打印堆栈跟踪
                    exception1.printStackTrace();

                    //返回一个错误信息
                    回报(的getString(R.string.IO_Exception_getFromLocation));

                //捕捉不正确经纬度值
                }赶上(抛出:IllegalArgumentException exception2){

                    //构造包含无效的参数消息
                    字符串为errorString =的getString(
                            R.string.illegal_argument_exception,
                            location.getLatitude(),
                            location.getLongitude()
                    );
                    //记录错误并打印堆栈跟踪
                    Log.e(LocationUtils.APPTAG,为errorString);
                    exception2.printStackTrace();

                    //
                    返回为errorString;
                }
                //如果反向地理code返回地址
                如果(地址=空&安培;!&安培; addresses.size()大于0){

                    //获取第一个地址
                    地址地址= addresses.get(0);

                    //格式的地址的第一行
                    字符串addressText =的getString(R.string.address_output_string,

                            //如果有一个街道地址,添加它
                            address.getMaxAddressLineIndex()> 0?
                                    address.getAddressLine(0):,

                            //局部性通常是一个城市
                            address.getLocality(),

                            //地址的国家
                            address.getCountryName()
                    );

                    //返回文本
                    返回addressText;

                //如果没有任何地址,发布消息
                } 其他 {
                  返回的getString(R.string.no_address_found);
                }
        }

        / **
         *这就是所谓一旦doInBackground()的方法完成。设置的文本
         *显示的地址的用户界面元素。此方法运行在UI线程上。
         * /
        @覆盖
        保护无效onPostExecute(字符串地址){

            //关闭进度条
            mActivityIndi​​cator.setVisibility(View.GONE);

            //设置地址在UI
            mAddress.setText(地址);
        }
    }

    / **
     *显示由谷歌返回一个对话框,播放服务,为
     *连接错误code
     *
     *从onConnectionFailed返回@参数错误$ C C错误code $
     * /
    私人无效showErrorDialog(INT错误code){

        //获取错误对话框,从谷歌Play业务
        对话errorDialog = GooglePlayServicesUtil.getErrorDialog(
            错误code,
            getActivity(),
            LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);

        //如果谷歌Play业务可以提供一个错误对话框
        如果(errorDialog!= NULL){

            //创建一个新DialogFragment中显示错误对话框
            ErrorDialogFragment errorFragment =新ErrorDialogFragment();

            //设置对话框中的DialogFragment
            errorFragment.setDialog(errorDialog);

            //显示在DialogFragment错误对话框
            errorFragment.show(getActivity()getSupportFragmentManager(),LocationUtils.APPTAG);
        }
    }

    / **
     *定义一个DialogFragment显示中产生的错误对话框
     * showErrorDialog。
     * /
    公共静态类ErrorDialogFragment扩展DialogFragment {

        //全球领域包含错误对话框
        私人对话mDialog;

        / **
         *默认构造函数。设置对话框字段设置为null
         * /
        公共ErrorDialogFragment(){
            超();
            mDialog = NULL;
        }

        / **
         *设置对话框,显示
         *
         *参数对话框中的一个错误对话框
         * /
        公共无效setDialog(对话对话框){
            mDialog =对话框;
        }

        / *
         *这个方法必须返回一个对话框,将DialogFragment。
         * /
        @覆盖
        公共对话onCreateDialog(包savedInstanceState){
            返回mDialog;
        }
    }
}
 

解决方案

采取一切code。在 onCreatView() 除了查看rootView 并把它放在 ONSTART()

I am trying to convert the code given for locationClient on google developer page from FragmentActivity to Fragment. I seem to be getting a null pointer exception in my onCreateView where i get the handle for the textView mLatLng = (TextView) getView().findViewById(R.id.lat_lng);

public class Hottest extends Fragment implements
        LocationListener,
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {

    // A request to connect to Location Services
    private LocationRequest mLocationRequest;

    // Stores the current instantiation of the location client in this object
    private LocationClient mLocationClient;

    // Handles to UI widgets
    private TextView mLatLng;
    private TextView mAddress;
    private ProgressBar mActivityIndicator;
    private TextView mConnectionState;
    private TextView mConnectionStatus;

    // Handle to SharedPreferences for this app
    SharedPreferences mPrefs;

    // Handle to a SharedPreferences editor
    SharedPreferences.Editor mEditor;

    /*
     * Note if updates have been turned on. Starts out as "false"; is set to "true" in the
     * method handleRequestSuccess of LocationUpdateReceiver.
     *
     */
    boolean mUpdatesRequested = false;

    /*
     * Initialize the Activity
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        Log.d("onCreatView", "inside onCreatView ");

        View rootView = inflater.inflate(R.layout.hottest, container, false);
     // Get handles to the UI view objects
        mLatLng = (TextView) getView().findViewById(R.id.lat_lng);
        mAddress = (TextView) getView().findViewById(R.id.address);
        mActivityIndicator = (ProgressBar) getView().findViewById(R.id.address_progress);
        mConnectionState = (TextView) getView().findViewById(R.id.text_connection_state);
        mConnectionStatus = (TextView) getView().findViewById(R.id.text_connection_status);

        // Create a new global location parameters object
        mLocationRequest = LocationRequest.create();

        /*
         * Set the update interval
         */
        mLocationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);

        // Use high accuracy
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        // Set the interval ceiling to one minute
        mLocationRequest.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);

        // Note that location updates are off until the user turns them on
        mUpdatesRequested = false;

        // Open Shared Preferences
        mPrefs = getActivity().getSharedPreferences(LocationUtils.SHARED_PREFERENCES, Context.MODE_PRIVATE);

        // Get an editor
        mEditor = mPrefs.edit();

        /*
         * Create a new location client, using the enclosing class to
         * handle callbacks.
         */
        mLocationClient = new LocationClient(getActivity(), this, this);

        return rootView;
    }

    /*
     * Called when the Activity is no longer visible at all.
     * Stop updates and disconnect.
     */
    @Override
    public void onStop() {

        // If the client is connected
        if (mLocationClient.isConnected()) {
            stopPeriodicUpdates();
        }

        // After disconnect() is called, the client is considered "dead".
        mLocationClient.disconnect();

        super.onStop();
    }
    /*
     * Called when the Activity is going into the background.
     * Parts of the UI may be visible, but the Activity is inactive.
     */
    @Override
    public void onPause() {

        // Save the current setting for updates
        mEditor.putBoolean(LocationUtils.KEY_UPDATES_REQUESTED, mUpdatesRequested);
        mEditor.commit();

        super.onPause();
    }

    /*
     * Called when the Activity is restarted, even before it becomes visible.
     */
    @Override
    public void onStart() {

        super.onStart();

        /*
         * Connect the client. Don't re-start any requests here;
         * instead, wait for onResume()
         */
        mLocationClient.connect();

    }
    /*
     * Called when the system detects that this Activity is now visible.
     */
    @Override
    public void onResume() {
        super.onResume();

        // If the app already has a setting for getting location updates, get it
        if (mPrefs.contains(LocationUtils.KEY_UPDATES_REQUESTED)) {
            mUpdatesRequested = mPrefs.getBoolean(LocationUtils.KEY_UPDATES_REQUESTED, false);

        // Otherwise, turn off location updates until requested
        } else {
            mEditor.putBoolean(LocationUtils.KEY_UPDATES_REQUESTED, false);
            mEditor.commit();
        }

    }

    /*
     * Handle results returned to this Activity by other Activities started with
     * startActivityForResult(). In particular, the method onConnectionFailed() in
     * LocationUpdateRemover and LocationUpdateRequester may call startResolutionForResult() to
     * start an Activity that handles Google Play services problems. The result of this
     * call returns here, to onActivityResult.
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        for (Fragment fragment : getActivity().getSupportFragmentManager().getFragments()) {
            fragment.onActivityResult(requestCode, resultCode, intent);
        }
        // Choose what to do based on the request code
        switch (requestCode) {

            // If the request code matches the code sent in onConnectionFailed
            case LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST :

                switch (resultCode) {
                    // If Google Play services resolved the problem
                    case Activity.RESULT_OK:

                        // Log the result
                        Log.d(LocationUtils.APPTAG, getString(R.string.resolved));

                        // Display the result
                        mConnectionState.setText(R.string.connected);
                        mConnectionStatus.setText(R.string.resolved);
                    break;

                    // If any other result was returned by Google Play services
                    default:
                        // Log the result
                        Log.d(LocationUtils.APPTAG, getString(R.string.no_resolution));

                        // Display the result
                        mConnectionState.setText(R.string.disconnected);
                        mConnectionStatus.setText(R.string.no_resolution);

                    break;
                }

            // If any other request code was received
            default:
               // Report that this Activity received an unknown requestCode
               Log.d(LocationUtils.APPTAG,
                       getString(R.string.unknown_activity_request_code, requestCode));

               break;
        }
    }

    /**
     * Verify that Google Play services is available before making a request.
     *
     * @return true if Google Play services is available, otherwise false
     */
    private boolean servicesConnected() {

        // Check that Google Play services is available
        int resultCode =
                GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());

        // If Google Play services is available
        if (ConnectionResult.SUCCESS == resultCode) {
            // In debug mode, log the status
            Log.d(LocationUtils.APPTAG, getString(R.string.play_services_available));

            // Continue
            return true;
        // Google Play services was not available for some reason
        } else {
            // Display an error dialog
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(), 0);
            if (dialog != null) {
                ErrorDialogFragment errorFragment = new ErrorDialogFragment();
                errorFragment.setDialog(dialog);
                errorFragment.show(getActivity().getSupportFragmentManager(), LocationUtils.APPTAG);
            }
            return false;
        }
    }

    /**
     * Invoked by the "Get Location" button.
     *
     * Calls getLastLocation() to get the current location
     *
     * @param v The view object associated with this method, in this case a Button.
     */
    public void getLocation(View v) {

        // If Google Play Services is available
        if (servicesConnected()) {

            // Get the current location
            Location currentLocation = mLocationClient.getLastLocation();

            // Display the current location in the UI
            mLatLng.setText(LocationUtils.getLatLng(getActivity(), currentLocation));
        }
    }

    /**
     * Invoked by the "Get Address" button.
     * Get the address of the current location, using reverse geocoding. This only works if
     * a geocoding service is available.
     *
     * @param v The view object associated with this method, in this case a Button.
     */
    // For Eclipse with ADT, suppress warnings about Geocoder.isPresent()
    @SuppressLint("NewApi")
    public void getAddress(View v) {

        // In Gingerbread and later, use Geocoder.isPresent() to see if a geocoder is available.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && !Geocoder.isPresent()) {
            // No geocoder is present. Issue an error message
            Toast.makeText(getActivity(), R.string.no_geocoder_available, Toast.LENGTH_LONG).show();
            return;
        }

        if (servicesConnected()) {

            // Get the current location
            Location currentLocation = mLocationClient.getLastLocation();

            // Turn the indefinite activity indicator on
            mActivityIndicator.setVisibility(View.VISIBLE);

            // Start the background task
            (new Hottest.GetAddressTask(getActivity())).execute(currentLocation);
        }
    }

    /**
     * Invoked by the "Start Updates" button
     * Sends a request to start location updates
     *
     * @param v The view object associated with this method, in this case a Button.
     */
    public void startUpdates(View v) {
        mUpdatesRequested = true;

        if (servicesConnected()) {
            startPeriodicUpdates();
        }
    }

    /**
     * Invoked by the "Stop Updates" button
     * Sends a request to remove location updates
     * request them.
     *
     * @param v The view object associated with this method, in this case a Button.
     */
    public void stopUpdates(View v) {
        mUpdatesRequested = false;

        if (servicesConnected()) {
            stopPeriodicUpdates();
        }
    }

    /*
     * Called by Location Services when the request to connect the
     * client finishes successfully. At this point, you can
     * request the current location or start periodic updates
     */
    @Override
    public void onConnected(Bundle bundle) {
        mConnectionStatus.setText(R.string.connected);

        if (mUpdatesRequested) {
            startPeriodicUpdates();
        }
    }

    /*
     * Called by Location Services if the connection to the
     * location client drops because of an error.
     */
    @Override
    public void onDisconnected() {
        mConnectionStatus.setText(R.string.disconnected);
    }

    /*
     * Called by Location Services if the attempt to
     * Location Services fails.
     */
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

        /*
         * Google Play services can resolve some errors it detects.
         * If the error has a resolution, try sending an Intent to
         * start a Google Play services activity that can resolve
         * error.
         */
        if (connectionResult.hasResolution()) {
            try {

                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(
                        getActivity(),
                        LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);

                /*
                * Thrown if Google Play services canceled the original
                * PendingIntent
                */

            } catch (IntentSender.SendIntentException e) {

                // Log the error
                e.printStackTrace();
            }
        } else {

            // If no resolution is available, display a dialog to the user with the error.
            showErrorDialog(connectionResult.getErrorCode());
        }
    }

    /**
     * Report location updates to the UI.
     *
     * @param location The updated location.
     */
    @Override
    public void onLocationChanged(Location location) {

        // Report to the UI that the location was updated
        mConnectionStatus.setText(R.string.location_updated);

        // In the UI, set the latitude and longitude to the value received
        mLatLng.setText(LocationUtils.getLatLng(getActivity(), location));
    }

    /**
     * In response to a request to start updates, send a request
     * to Location Services
     */
    private void startPeriodicUpdates() {

        mLocationClient.requestLocationUpdates(mLocationRequest, this);
        mConnectionState.setText(R.string.location_requested);
    }

    /**
     * In response to a request to stop updates, send a request to
     * Location Services
     */
    private void stopPeriodicUpdates() {
        mLocationClient.removeLocationUpdates(this);
        mConnectionState.setText(R.string.location_updates_stopped);
    }

    /**
     * An AsyncTask that calls getFromLocation() in the background.
     * The class uses the following generic types:
     * Location - A {@link android.location.Location} object containing the current location,
     *            passed as the input parameter to doInBackground()
     * Void     - indicates that progress units are not used by this subclass
     * String   - An address passed to onPostExecute()
     */
    protected class GetAddressTask extends AsyncTask<Location, Void, String> {

        // Store the context passed to the AsyncTask when the system instantiates it.
        Context localContext;

        // Constructor called by the system to instantiate the task
        public GetAddressTask(Context context) {

            // Required by the semantics of AsyncTask
            super();

            // Set a Context for the background task
            localContext = context;
        }

        /**
         * Get a geocoding service instance, pass latitude and longitude to it, format the returned
         * address, and return the address to the UI thread.
         */
        @Override
        protected String doInBackground(Location... params) {
            /*
             * Get a new geocoding service instance, set for localized addresses. This example uses
             * android.location.Geocoder, but other geocoders that conform to address standards
             * can also be used.
             */
            Geocoder geocoder = new Geocoder(localContext, Locale.getDefault());

            // Get the current location from the input parameter list
            Location location = params[0];

            // Create a list to contain the result address
            List <Address> addresses = null;

            // Try to get an address for the current location. Catch IO or network problems.
            try {

                /*
                 * Call the synchronous getFromLocation() method with the latitude and
                 * longitude of the current location. Return at most 1 address.
                 */
                addresses = geocoder.getFromLocation(location.getLatitude(),
                    location.getLongitude(), 1
                );

                // Catch network or other I/O problems.
                } catch (IOException exception1) {

                    // Log an error and return an error message
                    Log.e(LocationUtils.APPTAG, getString(R.string.IO_Exception_getFromLocation));

                    // print the stack trace
                    exception1.printStackTrace();

                    // Return an error message
                    return (getString(R.string.IO_Exception_getFromLocation));

                // Catch incorrect latitude or longitude values
                } catch (IllegalArgumentException exception2) {

                    // Construct a message containing the invalid arguments
                    String errorString = getString(
                            R.string.illegal_argument_exception,
                            location.getLatitude(),
                            location.getLongitude()
                    );
                    // Log the error and print the stack trace
                    Log.e(LocationUtils.APPTAG, errorString);
                    exception2.printStackTrace();

                    //
                    return errorString;
                }
                // If the reverse geocode returned an address
                if (addresses != null && addresses.size() > 0) {

                    // Get the first address
                    Address address = addresses.get(0);

                    // Format the first line of address
                    String addressText = getString(R.string.address_output_string,

                            // If there's a street address, add it
                            address.getMaxAddressLineIndex() > 0 ?
                                    address.getAddressLine(0) : "",

                            // Locality is usually a city
                            address.getLocality(),

                            // The country of the address
                            address.getCountryName()
                    );

                    // Return the text
                    return addressText;

                // If there aren't any addresses, post a message
                } else {
                  return getString(R.string.no_address_found);
                }
        }

        /**
         * A method that's called once doInBackground() completes. Set the text of the
         * UI element that displays the address. This method runs on the UI thread.
         */
        @Override
        protected void onPostExecute(String address) {

            // Turn off the progress bar
            mActivityIndicator.setVisibility(View.GONE);

            // Set the address in the UI
            mAddress.setText(address);
        }
    }

    /**
     * Show a dialog returned by Google Play services for the
     * connection error code
     *
     * @param errorCode An error code returned from onConnectionFailed
     */
    private void showErrorDialog(int errorCode) {

        // Get the error dialog from Google Play services
        Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
            errorCode,
            getActivity(),
            LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);

        // If Google Play services can provide an error dialog
        if (errorDialog != null) {

            // Create a new DialogFragment in which to show the error dialog
            ErrorDialogFragment errorFragment = new ErrorDialogFragment();

            // Set the dialog in the DialogFragment
            errorFragment.setDialog(errorDialog);

            // Show the error dialog in the DialogFragment
            errorFragment.show(getActivity().getSupportFragmentManager(), LocationUtils.APPTAG);
        }
    }

    /**
     * Define a DialogFragment to display the error dialog generated in
     * showErrorDialog.
     */
    public static class ErrorDialogFragment extends DialogFragment {

        // Global field to contain the error dialog
        private Dialog mDialog;

        /**
         * Default constructor. Sets the dialog field to null
         */
        public ErrorDialogFragment() {
            super();
            mDialog = null;
        }

        /**
         * Set the dialog to display
         *
         * @param dialog An error dialog
         */
        public void setDialog(Dialog dialog) {
            mDialog = dialog;
        }

        /*
         * This method must return a Dialog to the DialogFragment.
         */
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            return mDialog;
        }
    }
}
解决方案

Take all code in onCreatView()except View rootView and put it in onStart()

这篇关于Android的谷歌地图:尝试使用locationClient的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 05:27