Je le code suivant pour un fragment androïde écrit ici:Comment puis-je créer map! = Null?
fichier Java:
package com.WolfDev.ExercisePlanner;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
/**
* Created by WolfDev on 4/14/2014.
*/
public class TrackerFragment extends Fragment {
private GoogleMap googleMap;
//private boolean chronoRunning = false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag3_action, container, false);
SupportMapFragment supportMapFragment = SupportMapFragment.newInstance();
googleMap = supportMapFragment.getMap();
//googleMap.setMyLocationEnabled(true);
android.support.v4.app.FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.map, supportMapFragment).commit();
activityBody();
return rootView;
}
fichier Mise en page:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="6"
android:id="@+id/map"
class="com.google.android.gms.maps.MapFragment" >
</fragment>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
<Chronometer
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/chronometer"
android:text="@+id/chronometerDisplay"
android:gravity="center" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
<Button
android:layout_width="0px"
android:layout_height="match_parent"
android:text="START/STOP"
android:id="@+id/btnStartStop"
android:layout_weight="1"/>
<Button
android:layout_width="0px"
android:layout_height="match_parent"
android:text="LAP/RESET"
android:id="@+id/btnLapReset"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
Comme vous pouvez le voir dans le code, j'ai cette ligne a commenté:
//googleMap.setMyLocationEnabled(true);
Lorsque ce n'est pas commenté, je obtenez une erreur NullPointerException. Ma recherche m'a montré que cela se produit parce que la variable googleMap est nulle. Comment puis-je corriger cela afin qu'il ne soit plus nul?
D'où obtenez-vous le mapFragment? Je n'ai pas de variable avec ce nom. – Patr3xion
@ Patr3xion Je suppose que vous voudriez assigner 'SupportMapFragment.newInstance()' à un champ au lieu d'une variable locale. –