我有一個應用程序,有一個GPS按鈕來獲取您的位置,也是一個谷歌地圖的地方選擇器。只要手動打開應用程序的位置,大多數情況下都可以正常工作。警報圖標不會出現讓你打開像它應該的位置,還隨機提供了以下錯誤:Android GPS應用程序有時崩潰
D/AndroidRuntime: Shutting down 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 object reference at com.example.curtisboylan.myapplication.SearchScreen.onLocationChanged(SearchScreen.java:391) at com.google.android.gms.location.internal.zzk$zzb.handleMessage(Unknown Source) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) Application terminated.
我會附上下面的代碼:
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);
}
}
其還沒有真正回答爲什麼不問我要我的位置,如果它不是已經打開,其中的代碼應該做的 –