强制转换TextView时出现java.lang.NullPointerException

时间:2015-09-14 08:49:31

标签: java android android-fragments

当我访问带有片段的页面时,我想在TextView上显示纬度和经度的位置。

这是我的代码:

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import info.androidhive.materialdesign.R;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;


public class GpsFragment extends Fragment implements ConnectionCallbacks,
        OnConnectionFailedListener {

    private static String TAG = MainActivity.class.getSimpleName();

    public GpsFragment() {
        // Required empty public constructor
    }

    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
    private Location mLastLocation;

    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;

    // boolean flag to toggle periodic location updates
    private boolean mRequestingLocationUpdates = false;

    private LocationRequest mLocationRequest;

    public TextView lblLocation;

    // Location updates intervals in sec
    private static int UPDATE_INTERVAL = 10000; // 10 sec
    private static int FATEST_INTERVAL = 5000; // 5 sec
    private static int DISPLACEMENT = 10; // 10 meters

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_gps, container, false);

        lblLocation = (TextView)rootView.findViewById(R.id.lblLocation);

        // First we need to check availability of play services
        if (checkPlayServices()) {
            buildGoogleApiClient();
        }

        return rootView;
    }

    private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();
            lblLocation.setText(latitude + ", " + longitude);
        } else {
            //lblLocation.setText("(Couldn't get the location. Make sure location is enabled on the device)");
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getActivity());
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(getActivity().getApplicationContext(),
                        "This device is not supported.", Toast.LENGTH_LONG)
                        .show();
                getActivity().finish();
            }
            return false;
        }
        return true;
    }



    @Override
    public void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        checkPlayServices();
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {
        displayLocation();
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}

logcat错误:

Process: info.androidhive.materialdesign, PID: 2015
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
            at info.androidhive.materialdesign.activity.GpsFragment.displayLocation(GpsFragment.java:81)
            at info.androidhive.materialdesign.activity.GpsFragment.onConnected(GpsFragment.java:135)
            at com.google.android.gms.common.internal.zzk.zzh(Unknown Source)
            at com.google.android.gms.common.api.zzg.zznt(Unknown Source)
            at com.google.android.gms.common.api.zzg.onConnected(Unknown Source)
            at com.google.android.gms.common.api.zzi$2.onConnected(Unknown Source)
            at com.google.android.gms.common.internal.zzj$zzg.zzoD(Unknown Source)
            at com.google.android.gms.common.internal.zzj$zza.zzc(Unknown Source)
            at com.google.android.gms.common.internal.zzj$zza.zzs(Unknown Source)
            at com.google.android.gms.common.internal.zzj$zzc.zzoF(Unknown Source)
            at com.google.android.gms.common.internal.zzj$zzb.handleMessage(Unknown Source)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:1)

您在setText中使用displayLocation() onConnected(),该onStart()onCreateView()中调用TextView。这意味着已经调用了lblLocation,因此应该创建您的视图。

唯一的可能是您在fragment_gps.xml布局中没有spark-submit --status $submitID --master $master 2>&1 | grep "success" ID stored procedure