Android - Error en aplicación GoogleMap

 
Vista:

Error en aplicación GoogleMap

Publicado por Andrea (1 intervención) el 26/04/2017 12:31:15
Buenas,
Estoy haciendo un bloc de notas en el que pueda introducirle localización, que me debe mostrar al entrar en la nota.

He probado a hacerlo de muchas maneras, pero la que menos errores me crea es esta.



FATAL EXCEPTION: main
Process: andrea.gestordenotas, PID: 23800
java.lang.RuntimeException: Unable to start activity ComponentInfo{andrea.gestordenotas/andrea.gestordenotas.VerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2581)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2656)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1512)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5692)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at andrea.gestordenotas.VerActivity.onMapReady(VerActivity.java:113)
at andrea.gestordenotas.VerActivity.onCreate(VerActivity.java:78)
at android.app.Activity.performCreate(Activity.java:6144)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2528)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2656) 
at android.app.ActivityThread.access$800(ActivityThread.java:178) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1512) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:194) 
at android.app.ActivityThread.main(ActivityThread.java:5692) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)

Al crear una nota me introduce correctamente la dirección por string. Y si no le introduzco nada se crea correctamente el null. El problema reside en que al ver la nota, si esta tiene un valor en la dirección, se sale del programa dando el error anterior. En cambio si el valor es null si se abre sin mostrar el mapa y diciendo que no existen coordenadas (como lo programe). Es decir, el fallo solo es si la dirección no es null.

A continuación, pongo el layout y java concretos.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
public class VerActivity extends ActionBarActivity implements OnMapReadyCallback {
 
    String title,content;
    TextView TITLE,CONTENT;
    ManejadorDB DB;
 
    private String map;
    TextView textoMap;
 
    private GoogleMap mMap;
 
    /**
     * onCreate
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ver_nota);
 
        Bundle bundle = this.getIntent().getExtras();
 
        title = bundle.getString("title");
        content = bundle.getString("content");
        map = bundle.getString("map");
 
        TITLE = (TextView)findViewById(R.id.titulo);
        CONTENT = (TextView)findViewById(R.id.contenido);
        TITLE.setText(title);
        CONTENT.setText(content);
 
        textoMap = (TextView) findViewById(R.id.textoMapa);
 
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapa);
        mapFragment.getMapAsync(this);
 
        if (map.equals("")){
            textoMap.setText("Esta nota no tiene coordenadas");
            mapFragment.getView().setVisibility(View.GONE);
 
        } else {
            textoMap.setText(R.string.menuMap);
            onMapReady(mMap);
        }
 
    }
 
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
 
        try {
            Geocoder geocoder = new Geocoder(this);
            List<Address> addressList = geocoder.getFromLocationName(map, 1);
 
            if (addressList.size() > 0){
 
                Address address = addressList.get(0);
                double latitude = address.getLatitude();
                double longitude = address.getLongitude();
 
                MarkerOptions marker = new MarkerOptions();
                marker.position(new LatLng(latitude, longitude));
                marker.icon(BitmapDescriptorFactory.defaultMarker());
                marker.title(title);
                mMap.addMarker(marker);
 
                CameraUpdate cam = CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 14);
                mMap.animateCamera(cam);
            }
 
        } catch (IOException e) {
            Toast.makeText(this, "Servicio de geolocalizacion no disponible", Toast.LENGTH_SHORT).show();
        }
 
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
 
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            return;
        }
 
        googleMap.setMyLocationEnabled(true);
 
    }
 
    /**
     * Limpiamos el menu y creamos un menu nuevo
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu2, menu);
        super.onCreateOptionsMenu(menu);
 
        return true;
    }
 
    /**
     * Crea la actividad de la opcion del menu
     * Nos permitira volver a la pantalla principal
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
 
        switch (item.getItemId()){
            case R.id.editarNota:
                actividad("editar");
                return true;
 
            case R.id.eliminarNota:
                alert();
                return true;
 
            case R.id.menuSalir:
                actividad("salir");
                return true;
 
            default:
                return super.onOptionsItemSelected(item);
        }
    }
 
    /**
     * Actividad para las opciones editar y salir
     *
     * @param opcion
     */
    public void actividad(String opcion){
 
        if(opcion.equals("editar")){
            String type ="editar";
            Intent intent = new Intent(VerActivity.this,AgregarActivity.class);
            intent.putExtra("type",type);
            intent.putExtra("title",title);
            intent.putExtra("content",content);
            intent.putExtra("map", map);
            startActivity(intent);
 
        }else{
            if (opcion.equals("salir")){
                CookieSyncManager.createInstance(this);
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.removeAllCookie();
                Intent intent= new Intent(VerActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
    }
 
    /**
     * Actividad para la opcion eliminar
     * Alerta que vamos a eliminar una nota y nos pide confirmacion
     */
    private void alert(){
        AlertDialog alerta = new AlertDialog.Builder(this).create();
        alerta.setTitle("¿Eliminar nota?");
        alerta.setMessage("¿Esta seguro de querer eliminar la nota?");
        alerta.setButton("  Eliminar",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                delete();
            }
        });
        alerta.setButton2("Cancelar",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                return;
            }
        });
        alerta.show();
    }
 
    private void delete(){
        DB = new ManejadorDB(this);
        DB.eliminarNota(title);
        actividad("salir");
    }
 
}



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <TextView
        android:text="Titulo:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
    <TextView
        android:id="@+id/titulo"
        android:text=""
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
    <TextView
        android:text="Contenido:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
    <TextView
        android:id="@+id/contenido"
        android:text=""
        android:gravity="start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
    <TextView
        android:id="@+id/textoMapa"
        android:text="@string/menuMap"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
    <fragment
        android:id="@+id/mapa"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
 
</LinearLayout>


Espero respuestas, gracias.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder