Android GPS应用程序有时会崩溃

时间:2017-03-28 08:44:19

标签: java android gps

我的应用程序有一个GPS按钮来获取您的位置,还有一个Google Maps地方选择器。只要您手动打开应用程序的位置,这在大多数情况下都可以正常工作。警报图标似乎不会让您打开它应该的位置,它也会随机出现以下错误:

  

D / AndroidRuntime:关闭VM

              --------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.curtisboylan.myapplication, PID: 2443
              java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a
     

null对象引用                         at com.example.curtisboylan.myapplication.SearchScreen.onLocationChanged(SearchScreen.java:391)                         在com.google.android.gms.location.internal.zzk $ zzb.handleMessage(未知   资源)                         在android.os.Handler.dispatchMessage(Handler.java:102)                         在android.os.Looper.loop(Looper.java:154)                         在android.app.ActivityThread.main(ActivityThread.java:6119)                         at java.lang.reflect.Method.invoke(Native Method)                         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:886)                         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)   申请已终止。

我将附上以下代码:

public class SearchScreen extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
    public final static String EXTRA_MESSAGE = "com.example.curtisboylan.myapplication";

    private GoogleApiClient client;
    private GridViewAdapter mAdapter;
    private ArrayList<String> listType;
    private ArrayList<Integer> listIcon;
    private String repairtype;
    private GridView gridView;

    private TextView tv;

    private Button contBtn;
    private Button googleLocBtn;
    private Button gpsBtn;
    private boolean setGPSloc = false;

    private Location mLocation;
    private LocationManager locationManager;
    private long UPDATE_INTERVAL = 2 * 1000;  /* 10 secs */
    private long FASTEST_INTERVAL = 2000;
    private LocationRequest mLocationRequest;
    private com.google.android.gms.location.LocationListener listener;

    private TextView mLatitudeTextView;
    private TextView mLongitudeTextView;
    private TextView tv2;

    Double longitude;
    Double latitude;

    public static SearchScreen newInstance(){
        SearchScreen fragment = new SearchScreen();
        return fragment;
    }

    public SearchScreen(){}

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




        client = new GoogleApiClient.Builder(this.getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        checkLocation();


    }



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

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

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

        prepareList();
        repairtype ="";

        text = (TextView) view.findViewById(R.id.txt_TextDateTime);
        btn_date = (Button) view.findViewById(R.id.btn_datePicker);

        btn_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDate();
            }
        });

        contBtn = (Button) view.findViewById(R.id.button);
        contBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), TechnicianListView.class);
                intent.putExtra("message", repairtype);
                startActivity(intent);
            }
        });

        gpsBtn = (Button) view.findViewById(R.id.button3);
        gpsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv2.setText("" + getMyPosAddress(mLocation.getLatitude(), mLocation.getLongitude()));
            }
        });


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


        updateTextLabel();


        // prepared arraylist and passed it to the Adapter class
        mAdapter = new GridViewAdapter(getActivity(), listType, listIcon);

        // Set custom adapter to gridview
        gridView = (GridView) view.findViewById(R.id.gridView1);
        gridView.setAdapter(mAdapter);

        // Implement On Item click listener
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                Toast.makeText(getActivity(), "DEBUG " + mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
                repairtype = mAdapter.getItem(position);
            }
        });

        googleLocBtn = (Button) view.findViewById(R.id.googleLocBtn);
        googleLocBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                findPlace(v.findViewById(android.R.id.content));
            }
        });


        return view;
    }



    //Calling method DateFormat and Calendar
    DateFormat formatDateTime = DateFormat.getDateInstance();
    Calendar dateTime = Calendar.getInstance();
    //Creating Vars
    private TextView text;
    private Button btn_date;


    private void updateDate() {
        new DatePickerDialog(getActivity(), d, dateTime.get(Calendar.YEAR), dateTime.get(Calendar.MONTH), dateTime.get(Calendar.DAY_OF_MONTH)).show();
    }


    DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            dateTime.set(Calendar.YEAR, year);
            dateTime.set(Calendar.MONTH, monthOfYear);
            dateTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateTextLabel();
        }
    };


    private void updateTextLabel() {
        text.setText(formatDateTime.format(dateTime.getTime()));
    }


    public void prepareList() {
        listType = new ArrayList<String>();

        listType.add("di1");
        listType.add("screen1");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");

        listIcon = new ArrayList<Integer>();

        listIcon.add(R.drawable.camerabrokenicon);
        listIcon.add(R.drawable.screenrepairicon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
    }

    public void testBtn(View v) {
       // tv.setText("Welcome");

    }

    public void findPlace(View v) {
        try {
            Intent intent =
                    new PlaceAutocomplete
                            .IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                            .build(getActivity());
            startActivityForResult(intent, 1);
        } catch (GooglePlayServicesRepairableException e) {
            // TODO: Handle the error.
        } catch (GooglePlayServicesNotAvailableException e) {
            // TODO: Handle the error.
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(this.getContext(), data);
                Log.e("Tag", "Place: " + place.getAddress() + place.getPhoneNumber());

                ((TextView) getView().findViewById(R.id.textView))
                        .setText("" + place.getName());

            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {

            } else if (resultCode == RESULT_CANCELED) {
            }
        }
    }


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


    }

    @Override
    public void onStop() {
        super.onStop();
        client.disconnect();
    }


    private String getMyPosAddress(double dbLat, double dbLon) {
        String addressString = "No address found";
        Geocoder gc = new Geocoder(getContext(), Locale.getDefault());

        try {
            List<android.location.Address> gclist ;

            gclist =  gc.getFromLocation(dbLat, dbLon, 1);


            if (gclist.size() > 0) {
                android.location.Address address = gclist.get(0);

                addressString = "" + address.getAddressLine(0) + ", " + address.getAdminArea();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }



        return addressString;
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        } startLocationUpdates();
        mLocation = LocationServices.FusedLocationApi.getLastLocation(client);
        if(mLocation == null){
            startLocationUpdates();
        }
        if (mLocation != null) {
            latitude = mLocation.getLatitude();
            longitude = mLocation.getLongitude();
        } else {
        }


    }

    protected void startLocationUpdates() {
        // Create the location request
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(UPDATE_INTERVAL)
                .setFastestInterval(FASTEST_INTERVAL);
        // Request location updates
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(client,
                mLocationRequest, this);
        Log.d("reque", "--->>>>");
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection Suspended");
        client.connect();
    }

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

    @Override
    public void onLocationChanged(Location location) {
        String msg = "Updated Location: " +
                Double.toString(location.getLatitude()) + "," +
                Double.toString(location.getLongitude());

        latitude = mLocation.getLatitude();
        longitude = mLocation.getLongitude();
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    }

    private boolean checkLocation() {
        if(!isLocationEnabled())
            showAlert();
        return isLocationEnabled();
    }

    private void showAlert() {
        final AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        dialog.setTitle("Enable Location")
                .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
                        "use this app")
                .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(myIntent);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                    }
                });
        dialog.show();
    }

    private boolean isLocationEnabled() {
        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }



}

3 个答案:

答案 0 :(得分:1)

当调用onLocationChanged时,您似乎得到NullPointerException,因此您的Location对象为null。

您可以检查if(location!= null)以使其不会崩溃。

答案 1 :(得分:0)

添加BroadcastReceiver,侦听gps提供程序中的更改。通过这样做,您将知道用户何时关闭GPS。发生这种情况时,请更改计算用户位置的策略。

答案 2 :(得分:0)

请检查您的清单文件以获取适当的权限和其他事项如果您在Android m中运行,那么您需要转到设置 - &gt;应用程序 - &gt;选择您的应用程序并获取权限启用它..手动。

或者在代码中使用对话框询问权限

ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 200);