我正在尝试将动态谷歌地图添加到片段中,此片段包含一个工作正常的简单表单,当我添加谷歌地图部分时出现错误。
无法启动活动ComponentInfo {com.jdplee.proyecto / com.jdplee.proyecto.ClientDetailActivity}:java.lang.NullPointerException:尝试调用虚方法'com.jdplee.proyecto.ClientDetailFragment com.jdplee.proyecto.ClientDetailFragment空对象引用上的.newInstance()'
我所拥有的是mainActivity
,其中有一个打开详细视图的按钮,这是使用第二个活动完成的:
public class ClientDetailActivity extends AppCompatActivity {
public static final int REQUEST_ADD_TASK = 1;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client_detail);
ClientDetailFragment mClientDetailFragment = (ClientDetailFragment)
getSupportFragmentManager().findFragmentById(R.id.cd_fragment_container);
if (mClientDetailFragment == null) {
mClientDetailFragment = ClientDetailFragment.newInstance();
utilities.addFragmentToActivity(getSupportFragmentManager(), mClientDetailFragment, R.id.cd_fragment_container);
}
}
}
client_layout只有一个FrameLayout,片段将放在那里,片段类是:
public class ClientDetailFragment extends Fragment {
private static final int PERMISSION_REQUEST_CODE = 1;
private FusedLocationProviderClient mFusedLocationProviderClient;
public static ClientDetailFragment newInstance() {
return new ClientDetailFragment();
}
public ClientDetailFragment(){
//required empty constructor
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.client_detail_fragment, container, false);
if (getChildFragmentManager().findFragmentById(R.id.cd_maplocation) == null) {
SupportMapFragment mapFragment = new SupportMapFragment();
getChildFragmentManager()
.beginTransaction()
.replace(R.id.cd_maplocation, mapFragment)
.commit();
}
return root;
}
这个片段的布局里面有google map的framelayout:
<FrameLayout
android:id="@+id/cd_maplocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
这就是为什么我使用getChildFragment()
,对我来说这一切都有道理,我不明白为什么错误,我错过了什么?
答案 0 :(得分:0)
把这个东西放在onActivityCreated()
上if (getChildFragmentManager().findFragmentById(R.id.cd_maplocation) == null) {
SupportMapFragment mapFragment = new SupportMapFragment();
getChildFragmentManager()
.beginTransaction()
.replace(R.id.cd_maplocation, mapFragment)
.commit();
}