无法获得位置

时间:2017-01-12 18:53:53

标签: android android-fragments nullpointerexception location

我试图通过GoogleApiClient获取坐标。如果我运行应用程序,我会收到以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                  at com.example.android.pws.fragment.HomeFragment.onCreateView(HomeFragment.java:141)
                  at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
                  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1677)
                  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:536)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:158)
                  at android.app.ActivityThread.main(ActivityThread.java:7230)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

我不知道解决这个问题。我已经在互联网上搜索但没有任何作用。有人可以帮助我吗?

代码:

public class HomeFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener,
    GoogleApiClient.ConnectionCallbacks, com.google.android.gms.location.LocationListener {

private static final String TAG = HomeFragment.class.getSimpleName();

private static final int REQUEST_CODE_PERMISSION = 2;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;
private LocationListener listener;

TextView textView;
TextView textView3;


private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0;
private static final int REQUEST_CODE_SOME_FEATURES_PERMISSIONS=0;

Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
String lat, lon;


private String mParam1;
private String mParam2;


private OnFragmentInteractionListener mListener;

public HomeFragment() {

}


public static HomeFragment newInstance(String param1, String param2) {
    HomeFragment fragment = new HomeFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    View view = inflater.inflate(R.layout.fragment_home,
            container, false);

    try {
        if (ActivityCompat.checkSelfPermission(getActivity(), mPermission)
                != MockPackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(getActivity(), new String[]{mPermission},
                    REQUEST_CODE_PERMISSION);

            // If any permission above not allowed by user, this condition will
            //execute every time, else your else part will work
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    buildGoogleApiClient();





    TextView textView = (TextView) view.findViewById(R.id.textView);
    TextView textView3 = (TextView) view.findViewById(R.id.textView3);

    textView.setText(lat);
    textView3.setText(lon);



    int hasLocationPermission = ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION );
    int hasSMSPermission = ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.SEND_SMS );
    int hasCoarseLocation = ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION);
    List<String> permissions = new ArrayList<String>();
    if( hasLocationPermission != PackageManager.PERMISSION_GRANTED ) {
        permissions.add( android.Manifest.permission.ACCESS_FINE_LOCATION );
    }

    if( hasSMSPermission != PackageManager.PERMISSION_GRANTED ) {
        permissions.add( android.Manifest.permission.SEND_SMS );
    }

    if (hasCoarseLocation != PackageManager.PERMISSION_GRANTED) {
        permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
    }

    if( !permissions.isEmpty() ) {
        requestPermissions( permissions.toArray( new String[permissions.size()] ), REQUEST_CODE_SOME_FEATURES_PERMISSIONS );
    }

    Button button = (Button) view.findViewById(R.id.push_button);





    SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
    final String telNumber = pref.getString("number", null);
    final String message = "";




    button.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

            if (!TextUtils.isEmpty(telNumber)) {


                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(telNumber, null, message, null, null);
                Toast.makeText(getActivity().getApplicationContext(), "SMS sent.",
                        Toast.LENGTH_LONG).show();
                openDialer();





            }
            else {
                Toast.makeText(getActivity().getApplicationContext(), "Er is geen emergency contact toegevoegd.",
                        Toast.LENGTH_LONG).show();
            }



        }
    });

    return view;




}





private void openDialer() {
    Intent intent = new Intent(Intent.ACTION_DIAL);
    intent.setData(Uri.parse("tel:0123456789"));
    startActivity(intent);
}


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch ( requestCode ) {
        case REQUEST_CODE_SOME_FEATURES_PERMISSIONS: {
            for( int i = 0; i < permissions.length; i++ ) {
                if( grantResults[i] == PackageManager.PERMISSION_GRANTED ) {
                    Log.d( "Permissions", "Permission Granted: " + permissions[i] );
                } else if( grantResults[i] == PackageManager.PERMISSION_DENIED ) {
                    Log.d( "Permissions", "Permission Denied: " + permissions[i] );
                }
            }
        }
        break;
        default: {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

@Override
public void onConnected(Bundle bundle) {


    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(100); // Update location every second

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
                    ,10);
        }
        return;
    }

    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        lat = String.valueOf(mLastLocation.getLatitude());
        lon = String.valueOf(mLastLocation.getLongitude());

    }

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {
    lat = String.valueOf(location.getLatitude());
    lon = String.valueOf(location.getLongitude());
}



@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    buildGoogleApiClient();
}

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


}

@Override
public void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mGoogleApiClient.disconnect();
}








// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}


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

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

2 个答案:

答案 0 :(得分:0)

崩溃是因为您尝试将文本设置为具有空指针引用的文本视图。检查布局fragment_home.xml是否具有带有textview和textview3的TextView。崩溃发生在HomeFragment的第141行。

答案 1 :(得分:0)

您的一个观看次数textViewtextView3未在Home Fragment.xml中分配了ID