【问题标题】:Setting up view returns null pointer when location settings request is refused?位置设置请求被拒绝时设置视图返回空指针?
【发布时间】:2016-10-06 07:49:59
【问题描述】:

我遇到了这个问题,当用户拒绝在弹出窗口中打开他们的Location 设置时,我的Fragment 中的Views 返回 null。我似乎无法在Fragment 中引用任何Views。我想这是因为Location 请求View 的弹出对话框取代了我的Fragment View,但我不知道如何在Fragment 中访问Views。这是我的尝试:

private View fragmentView;
private View progressOverlay;
private View noPostsView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (fragmentView == null) {
        fragmentView = inflater.inflate(R.layout.posts_tab, container, false);
        setupActivity(savedInstanceState);
        progressOverlay = fragmentView.findViewById(R.id.progress_overlay);
        progressOverlay.setVisibility(View.VISIBLE);
        noPostsView = fragmentView.findViewById(R.id.no_posts_layout);
        setupLocation();
    }
    return fragmentView;
}

private void setupLocation() {
    Context context = getContext();
    if(locationService == null) {
        locationService = new LocationService(context, new LocationUpdateListener() {
            @Override
            public void canReceiveLocationUpdates() {

            }

            @Override
            public void cannotReceiveLocationUpdates() {
                createSettingsRequest();
                //well we know we cant receive updates so we have to create a settings request
            }

            //update location to our servers for tracking purpose
            @Override
            public void updateLocation(Location location) {
                if (location != null) {
                    //Populate Recycler View
                    databaseQuery.getPublicPosts(location, progressOverlay, fragmentView, getContext());
                }
            }

            @Override
            public void updateLocationName(String localityName, Location location) {
                locationService.stopLocationUpdates();
            }
        });
        locationService.startUpdates();
    }
}

private void createSettingsRequest() {
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(30 * 1000);
    locationRequest.setFastestInterval(5 * 1000);
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);
    builder.setAlwaysShow(true); //this is the key ingredient

    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(locationService.mGoogleApiClient
                    , builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates state = result.getLocationSettingsStates();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    // All location settings are satisfied. The client can initialize location
                    // requests here.
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    // Location settings are not satisfied. But could be fixed by showing the user
                    // a dialog.
                    try {
                        // Show the dialog by calling startResolutionForResult(),
                        // and check the result in onActivityResult().
                        status.startResolutionForResult(getActivity(), REQUEST_LOCATION);
                    } catch (IntentSender.SendIntentException e) {
                        FirebaseCrash.report(e);
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    // Location settings are not satisfied. However, we have no way to fix the
                    // settings so we won't show the dialog.
                    break;
            }
        }
    });
}

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // Check for the integer request code originally supplied to startResolutionForResult().
            case REQUEST_LOCATION:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        break;
                    case Activity.RESULT_CANCELED:
                        setupNoPostsView();
                        break;
                }
                break;
        }
    }

private void setupNoPostsView() {
    progressOverlay.setVisibility(View.GONE);
    noPostsView.setVisibility(View.VISIBLE);
    RecyclerView recyclerView = (RecyclerView) fragmentView.findViewById(R.id.rv_posts_feed);
    recyclerView.setVisibility(View.GONE);
    TextView noPosts = (TextView) noPostsView.findViewById(R.id.no_posts_text);
    noPosts.setText(R.string.permission_location_rationale);
}

如果用户在允许Location Services 时单击No,我只想调用setupNoPostsView,但无论出于何种原因,当我尝试设置Visibility = View.GONE 时,progressOverlay View 会不断返回null。关于如何解决这个问题的任何想法?

按照第一个答案的要求,这里更新我的布局:

片段.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/posts_tab"
    tools:showIn="@layout/app_bar_news_feed" tools:context=".news_feed">

    <include layout="@layout/include_progress_overlay"/>

    <include layout="@layout/no_posts"/>

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/rv_posts_feed"
        android:visibility="gone"
        />

</FrameLayout>

no_posts.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:id="@+id/no_posts_layout"
    android:visibility="gone"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:textSize="16sp"
        android:layout_gravity="center"
        android:gravity="center"
        android:textAlignment="center"
        android:id="@+id/no_posts_text" />

</FrameLayout>

【问题讨论】:

  • 您是否调用了正确的布局?您是否在清单文件中定义了活动?
  • 究竟是什么 NPE - 你能发布堆栈跟踪吗?

标签: java android android-fragments google-location-services


【解决方案1】:

那么,方法

status.startResolutionForResult(getActivity(), REQUEST_LOCATION);

正在调用由 google play 服务提供的新活动,该活动显示打开位置设置的对话框。让我们将 A 称为您的活动,将 B 称为 Google Play 服务提供的活动。可能在创建 B 时,由于内存压力或您更改了设备的方向, A 被销毁。当您在 B 上选择“拒绝”时,会在 Android 重新创建视图之前调用回调“onActivityResult”(这实际上是可能的)。所以......你必须以不同的方式管理这种情况,例如在你的 onAcvityResult 上设置一种标志。示例:

private Integer myResult = null;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (REQUEST_LOCATION == requestCode) {
        View root = getView();
        if (root != null) { // Consider also isResumed()
            // you can operate on your views
            applyLogicForResult(resultCode);
        } else {
            myResult = resultCode;
        }
    }
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // Consider also onResume()
    if (myResult != null) {
        applyLogicForResult(myResult);
        myResult = null;
    }
}

【讨论】:

  • 这太棒了。非常感谢!经过一番修修补补,我得到了它的实际工作。我真的很感激!
【解决方案2】:
  1. 您使用的是哪种布局?您可以为片段使用框架布局。 (你需要回忆一件事,框架布局一次只能显示一个子布局)
  2. 将内容放在这个框架布局中,你还必须添加一个布局,即文本视图布局,它说位置不可用。在开始时,这个文本视图的视图属性应该被隐藏。

    <FrameLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent">
    
    <android.support.v7.widget.RecyclerView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/rv"
       />
       <TextView
           android:id="@+id/error"
           android:layout_gravity="left|center|right"
           android:layout_width="match_parent"
           android:visibility="gone"
           android:layout_height="wrap_content"
           android:text="No location available"
           android:textAlignment="center" />
    </FrameLayout>
    

类似的东西..^

  1. 现在来看java代码

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // Check for the integer request code originally supplied to startResolutionForResult().
            case REQUEST_LOCATION:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        break;
                    case Activity.RESULT_CANCELED:
                        setupNoPostsView();
                        break;
                }
                break;
        }
    }
    
    
    
    private void setupNoPostsView() 
    {
        RecyclerView recyclerView = (RecyclerView) fragmentView.findViewById(R.id.rv_posts_feed);
        recyclerView.setVisibility(View.GONE);
        textView1.setVisibility(View.VISIBLE);
    
     }
    

【讨论】:

  • 嘿,我确实按照你的要求做了。我上传了我需要的 XML 文件,但我仍然不断收到 NPE 异常。任何帮助将不胜感激。
猜你喜欢
  • 2011-03-18
  • 1970-01-01
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多