【问题标题】:NullPointerException declaring Intent in extended FragmentActivityNullPointerException 在扩展的 FragmentActivity 中声明 Intent
【发布时间】:2015-06-09 22:56:58
【问题描述】:

我已经有一段时间了。我已经搜索并尝试了我所看到的一切。我无法宣布这个该死的活动。我有一个 MarkerActivity 用于在我的地图上创建标记。单击时,我希望他们打开一个活动并传递一个变量。我已经尝试了所有方法并不断崩溃NullPointerException。代码如下:

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tapmap.app.tapmapapp" >

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" /><meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyAksheZLMAALUfLHKWOsfTFCz7iP_KwpCE" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".BarBrewry"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/title_activity_bar_brewry"
        android:theme="@style/FullscreenTheme" >
    </activity>
    <activity
        android:name=".MarkerActivity"
        android:label="@string/title_activity_marker">
    </activity>
</application>
</manifest>

Marker.java:

package com.tapmap.app.tapmapapp;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.common.api.GoogleApiClient;


public class MarkerActivity extends android.support.v4.app.FragmentActivity    implements GoogleMap.OnMarkerClickListener {
public Marker myMarker;
public LatLng latLng;
public String venueid;
public String venuename;
public String[] taps;
public String address;
public Integer markid;

public void setUpMap() {

    MapsActivity.mMap.setOnMarkerClickListener(this);
    //googleMap.setOnInfoWindowClickListener(listener);
    myMarker = MapsActivity.mMap.addMarker(new MarkerOptions()
            .position(latLng)
            .title(venuename)
            .snippet("Check Taps/Get Directions")
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.tmico))
     );
}

@Override
public boolean onMarkerClick(final Marker marker) {
    Log.i("RetrieveFeedTask", MarkerActivity.this + "Marker Clicked" + MapsActivity.venues.get(markid).venuename);
    try {
        Intent bar = new Intent(MarkerActivity.this, BarBrewry.class);
       // bar.putExtra("venuename", venuename);
        //this.startActivity(bar);
    } catch(Exception vo) {
        Log.i("RetrieveFeedTask", "Error opening: " + vo.getMessage());
    }
    return true;
}
}

堆栈跟踪:

9153-9153/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
            at android.content.ComponentName.<init>(ComponentName.java:75)
            at android.content.Intent.<init>(Intent.java:3662)
            at com.tapmap.app.tapmapapp.MarkerActivity.onMarkerClick(MarkerActivity.java:50)
            at com.google.android.gms.maps.GoogleMap$10.zza(Unknown Source)
            at com.google.android.gms.maps.internal.zzn$zza.onTransact(Unknown Source)
            at android.os.Binder.transact(Binder.java:347)
            at com.google.android.gms.maps.internal.bd.a(SourceFile:84)
            at com.google.maps.api.android.lib6.d.as.b(Unknown Source)
            at com.google.maps.api.android.lib6.gmm6.c.e.a(Unknown Source)
            at com.google.maps.api.android.lib6.gmm6.n.av.a(Unknown Source)
            at com.google.maps.api.android.lib6.gmm6.n.be.a(Unknown Source)
            at com.google.maps.api.android.lib6.gmm6.n.bd.a(Unknown Source)
            at com.google.maps.api.android.lib6.gmm6.n.bt.d(Unknown Source)
            at com.google.maps.api.android.lib6.gmm6.n.ak.onSingleTapConfirmed(Unknown Source)
            at com.google.maps.api.android.lib6.gmm6.h.g.onSingleTapConfirmed(Unknown Source)
            at com.google.maps.api.android.lib6.gmm6.h.i.handleMessage(Unknown Source)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

地图活动

package com.tapmap.app.tapmapapp;

import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.common.api.GoogleApiClient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class MapsActivity extends FragmentActivity implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

public static GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
public static final String TAG = MapsActivity.class.getSimpleName();
public static List<MarkerActivity> venues = new ArrayList<MarkerActivity>();

private LocationRequest mLocationRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    setUpMapIfNeeded();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds
}

@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    super.onPause();
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}

/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #mMap} is not null.
 * <p/>
 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
 * install/update the Google Play services APK on their device.
 * <p/>
 * A user can return to this FragmentActivity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
 * have been completely destroyed during this process (it is likely that it would only be
 * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
 * method in {@link #onResume()} to guarantee that it will be called.
 */
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            try {
                setUpMap();
            } catch(IOException ioe){
                //nothing
            }
        }
    }
}

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap()throws IOException {
    mMap.setMyLocationEnabled(true);
    Log.i("MapsActivity","calling get locs");
    try {
        Log.i("RetrieveFeedTask", "Starting Call");

        new RetrieveFeedTask().execute("http://fltapmap.com/get-locs.php");
    } catch (Exception alle) {
        Log.i("RetrieveFeedTask", "Error" + alle.getMessage());
    }
}

@Override
public void onConnected(Bundle bundle) {
    Log.i(TAG, "Location services connected.");
    Location location =     LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) {
                  LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    else {
        handleNewLocation(location);
    }
}
private void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());
    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();
    LatLng latLng = new LatLng(currentLatitude, currentLongitude);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    CameraUpdate zoom=CameraUpdateFactory.zoomTo(10);
    mMap.animateCamera(zoom);
}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "Location services suspended. Please reconnect.");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();
        }
    } else {
        Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}

@Override
public void onLocationChanged(Location location) {
    handleNewLocation(location);
}
}

BarBrewry 现在是酒吧准系统,仅用于测试

package com.tapmap.app.tapmapapp;

import com.tapmap.app.tapmapapp.util.SystemUiHider;

import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

public class BarBrewry extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
}

【问题讨论】:

  • 问题出在 MarkerActivity.java,请添加该代码。
  • 抱歉,添加哪个代码?
  • 抱歉,marker.java 是带有清单代码的块中的第一个代码
  • 我现在看到了。看起来您正在创建一个活动列表,但这是行不通的。 List&lt;MarkerActivity&gt; venues = new ArrayList&lt;MarkerActivity&gt;();你到底想在这里完成什么?
  • 很难弄清楚你想在这里做什么,但看起来主要的问题是你没有使用startActivity() 启动 MarkerActivity,所以 MarkerActivity 从来没有有效的上下文.我认为你在这里做的最好的事情是将你所有的代码从 MarkerActivity 合并到 MapsActivity 中,并摆脱 MarkerActivity。

标签: java android google-maps android-intent


【解决方案1】:

也许你需要实现 public void onCreate(Bundle savedInstanceState) 方法..

【讨论】:

  • 我尝试将它添加到没有代码但仍然相同的错误的类中。
【解决方案2】:

这是因为您在该行中使用了错误的上下文:

    Intent bar = new Intent(MarkerActivity.this, BarBrewry.class);
    bar.putExtra("venuename", venuename);
    this.startActivity(bar);

this 不是内部类中的有效上下文。尝试使用:

    MarkerActivity.this.startActivity(bar);

此外,您必须在 MarkerActivity 中实现 onCreate,否则永远不会存在此活动的实例:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
}

我不完全知道你想用 MarkerActivity 实现什么,但就像 cmets 中提到的 Daniel Nugent 一样,你应该考虑将你的 MarkerActivityMapsActivity 合并。

【讨论】:

  • 我试过了,还是不行。只是再次尝试确定,同样的错误。
  • 您也可以尝试使用MapsActivity.this.startActivity(bar);。如果这也不起作用,请尝试在您的 Intent 中使用 MapsActivity.this
  • 我收到“MapsActivity.this is not and enclosure class”错误
  • 当然,抱歉,这是个错误的建议。我相信清单中的定义或类似的东西有问题,但我看不出有什么问题。也许尝试在 android:name 清单中的活动定义中使用完整的包名称。
  • 没有变化 :( 这太糟糕了!
猜你喜欢
  • 2012-09-10
  • 2019-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
  • 2017-01-01
  • 2020-05-15
相关资源
最近更新 更多