首页 > 解决方案 > Fragment 未附加到 FragmentManager

问题描述

我尝试在显示为片段的 googlemap 上显示我的位置。片段布局代码为:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/window_background_color"
android:clickable="false">

<!-- Toolbar  -->

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:background="@color/primary_color"
    android:elevation="1dp"
    android:minHeight="?attr/actionBarSize"
    android:titleTextAppearance="@style/TextAppearance.AppCompat.Body1"
    app:popupTheme="@style/Theme.AppCompat">

    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:maxLines="1"
        android:text="@string/toolbar"
        android:textColor="@android:color/white"
        android:textSize="24sp" />
</androidx.appcompat.widget.Toolbar>

<RelativeLayout
    android:id="@+id/test"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/toolbar"
    android:background="#1c3049"
    android:orientation="horizontal">

    <Button
        android:id="@+id/help"
        android:layout_width="45dp"
        android:layout_height="wrap_content"
        android:background="?attr/colorAccent"
        android:text="@string/help" />

    <Spinner
        android:id="@+id/spnCategory"
        android:layout_width="44dp"
        android:layout_height="match_parent"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:gravity="end" />

    <TextView
        android:id="@+id/mymess"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="95dp"
        android:gravity="center_vertical|center_horizontal"
        android:textColor="@android:color/white"
        android:textSize="14sp" />
</RelativeLayout>

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/test"
    android:orientation="vertical" />

片段从 mainActivity 显示:

FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
ActivityMap mFragment = new ActivityMap();
mTransaction.add(R.id.fragment, mFragment);
mTransaction.commit();

我从以下位置调用 getUserPosition:

@Override
public void onLocationChanged(Location location) {
    mCurrentLocation = location;
    getUserPosition(location.getLatitude(), location.getLongitude());
}

我的 getUserPosition 代码是:

  public void getUserPosition(double latitude, double longitude) {

    mCurrentLatitude = latitude;
    mCurrentLongitude = longitude;

    if (mIsMapVisible && isNetworkAvailable()) {
        TextView mytext = Objects.requireNonNull(getActivity()).findViewById(R.id.mymess));

        Geocoder geocoder = new Geocoder(getActivity(), Locale.ENGLISH);
        List<Address> addresses;
        try {
            addresses = geocoder.getFromLocation(mCurrentLatitude, mCurrentLongitude, 1);
            if ((addresses.size()>0)) {
                String str = addresses.get(0).getAddressLine(0);
                if(str.contains(",")) {
                    mytext.setText(str.substring(0, str.indexOf(",")));
                } else {
                    mytext.setText(str);
                }
            } else {
                mytext.setText(R.string.no_adr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
            String temp = mCurrentLatitude + "," + mCurrentLongitude;
            mytext.setText(temp);
        }
    }

    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
            new LatLng(mCurrentLatitude, mCurrentLongitude),
            Utils.ARG_DEFAULT_MAP_ZOOM_LEVEL);

    mMap.animateCamera(cameraUpdate);

}

最后这是问题部分:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getLayoutInflater().getContext().getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager != null ? connectivityManager.getActiveNetworkInfo() : null;
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

在这里,我收到下一条错误消息:E/UncaughtException: java.lang.IllegalStateException: onGetLayoutInflater() 在 Fragment 附加到 FragmentManager 之前无法执行。

我第一次运行应用程序工作完美。第二次我得到错误。依此类推,直到我的设备询问是否要关闭应用程序,因为他停止继续。我接受,下一次运行完美。然后……再次出现垃圾邮件问题。

有什么建议吗?

标签: androidgoogle-mapsandroid-fragments

解决方案


Fragments有自己的生命周期。在处理片段时,您始终应该考虑它们可能是分离的、隐藏的或它们的状态已经保存。

可能是因为您过早地收听位置更改事件,所以问题正在发生。但是,即使您在注册位置侦听器时进行了更改,以安全的方式获取Context(or Activity) 也是一个好习惯(因为分离时,Context/Actvity将为空)。

所以,我建议:

private boolean isNetworkAvailable() {
    boolean result = false;
    Context context = getContext();
    if(context != null) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager != null ? connectivityManager.getActiveNetworkInfo() : null;
        result = activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    return result;
}

FragmentgetContext()方法。所以,你可以替换getLayoutInflater()getContext()


推荐阅读