- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在开发一个应用程序,获取用户的当前位置并将其显示在 map 上,以及屏幕上的纬度和经度,到目前为止一切都很顺利, map 显示我当前的位置,并使用此代码在屏幕上显示纬度和经度
@Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
当我想在服务器上发送这个纬度和经度时出现问题,它抛出 NUll 指针异常
01-04 23:27:38.759 29286-29286/io.xgear.geotag E/AndroidRuntime: FATAL
EXCEPTION: main
Process: io.xgear.geotag, PID: 29286
java.lang.NullPointerException
at io.xgear.geotag.MainActivity$GeoTagTask.<init>(MainActivity.java:234)
at io.xgear.geotag.MainActivity$1.onClick(MainActivity.java:181)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19270)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
这是获取要发送的纬度和经度的代码
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private final String shopCode;
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
private boolean isConnect;
GeoTagTask(String shopId) {
shopCode = shopId;
isConnect = false;
}
@Override
protected Boolean doInBackground(Void... params) {
boolean res = false;
try {
ContentValues nameValuePairs = new ContentValues();
nameValuePairs.put("Id", shopCode);
nameValuePairs.put("lat", lat);
nameValuePairs.put("lng", lng);
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
Log.i("Latitude", lat+"");
Post post = new Post(getApplicationContext());
String result = "";
// isConnect = post.isConnected();
// if(isConnect) {
result = post.doPost(nameValuePairs);
jsonObj = new JSONObject(result);
Log.i("Result", result+"");
if(jsonObj.getInt("success") == 1)
res = true;
// }
} catch (JSONException e) {
e.printStackTrace();
}
return res;
}
这是完整的代码
package io.xgear.geotag;
import android.Manifest;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import android.support.v4.app.Fragment;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import io.xgear.geotag.helper.Post;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
private GeoTagTask mAuthTask = null;
GPSTracker gps;
private JSONObject jsonObj;
// UI references.
private EditText txtShopCode;
private EditText lblAddress;
private View mProgressView;
private View mGeoTagForm;
private Button btnGeoTag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtShopCode = (EditText) findViewById(R.id.txtShopCode);
btnGeoTag = (Button) findViewById(R.id.btnGeoTag);
mGeoTagForm = (View) findViewById(R.id.geoTagForm);
mProgressView = findViewById(R.id.geoTagProgress);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
btnGeoTag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String shopid = txtShopCode.getText().toString();
boolean cancel = false;
View focusView = null;
//txtShopCode.setInputType(InputType.TYPE_CLASS_NUMBER);
if (TextUtils.isEmpty(shopid)) {
txtShopCode.setError(getString(R.string.error_field_required));
focusView = txtShopCode;
cancel = true;
}
else {
showProgress(true);
mAuthTask = new GeoTagTask(shopid);
mAuthTask.execute((Void) null);
}
}
});
}
//
// public void btnGeoTag_Click(View v){
//
// }
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
mGeoTagForm.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private final String shopCode;
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
private boolean isConnect;
GeoTagTask(String shopId) {
shopCode = shopId;
isConnect = false;
}
@Override
protected Boolean doInBackground(Void... params) {
boolean res = false;
try {
ContentValues nameValuePairs = new ContentValues();
nameValuePairs.put("Id", shopCode);
nameValuePairs.put("lat", lat);
nameValuePairs.put("lng", lng);
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
Log.i("Latitude", lat+"");
Post post = new Post(getApplicationContext());
String result = "";
// isConnect = post.isConnected();
// if(isConnect) {
result = post.doPost(nameValuePairs);
jsonObj = new JSONObject(result);
Log.i("Result", result+"");
if(jsonObj.getInt("success") == 1)
res = true;
// }
} catch (JSONException e) {
e.printStackTrace();
}
return res;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
// Intent intent = new Intent(LoginActivity.this, MainActivity.class);
// intent.putExtra("jsonObj", jsonObj.toString());
// startActivity(intent);
txtShopCode.getText().clear();
txtShopCode.requestFocus();
Toast.makeText(getBaseContext(), "Your shop is geo tagged ", Toast.LENGTH_LONG).show();
} else {
// if(isConnect){
// mPasswordView.setError(getString(R.string.error_incorrect_password));
// mPasswordView.requestFocus();
// }
// else
Toast.makeText(getBaseContext(), R.string.geoTagError, Toast.LENGTH_LONG).show();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
@Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_main, menu);
// return true;
// }
}
更新我已在 GeoTagTask 中添加了这些行,按钮正在工作,应用程序没有崩溃,但我不确定如果位置更改它是否会工作,因为
if( location != null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
给我错误。
我添加的行
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
最佳答案
问题出在 GeoTagTask
内部,
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
您正在访问未初始化的变量。
将 onCreate location 设置为全局变量,
public class MainActivity extends FragmentActivity implements LocationListener {
Location location;
void onCreate() {
....
location = locationManager.getLastKnownLocation(provider);
....
}
}
在GeoTagTask
中使用全局变量,
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
...
}
关于java - 纬度和经度为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34597831/
我正在开发一个应用程序,用户可以在其中搜索其位置附近的项目。 当用户注册我的服务时,会获取他们的经/纬度坐标(这实际上是从邮政编码中获取的,然后通过 Google 查找经度/纬度坐标)。当用户添加一个
所以:我有以下函数,改编自在线找到的公式,它采用两个纬度/经度坐标并计算它们之间的距离(以英里为单位)(沿着球形地球): public static double distance (double l
我有一个给定点(经度、纬度),我想获取给定点 5 英里半径范围内的所有点范围? 最佳答案 我只是在这里猜测,但我认为您需要找到一种不同的方法。如果您尝试使用 Foursquare、Google map
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 5 年前。
我找到了一些代码,用于将纬度/经度转换为给定图像上的像素,反之亦然。我将其移植到 JavaScript,但在纬度上得到了不正确的返回值。我测试了原始的、未修改的代码,它给出了同样的不准确之处。下面是带
我用了AstroPy EarthLocation 获取传播卫星轨道的纬度、经度和高度 loc = coord.EarthLocation(*itrs.cartesian.xyz)。现在,我尝试使用 n
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: how to do location based search Getting similar longit
我有一个超过 15000 个经纬度坐标的列表。给定任何 X、Y 坐标,在列表中找到最近坐标的最快方法是什么? 最佳答案 您将需要使用名为 Voronoi diagram 的几何结构。 .这将平面划分为
For people interested in this topic: the accepted answer involves some concepts that I think are wel
我的应用程序上有一张 map ,它显示 2 种注释:位置和位置集群。当我放大集群时,集群会展开以显示集群中包含的位置。当这些位置添加到 map 时,其父簇的坐标将存储在注释对象中。我想要做的是制作一个
关于纬度/经度计算的简单问题。 我想获取一个值集,例如Lat: 55.123456 Long -6.123456 并计算出任意距离的四个点。 作为给定的正方形,我想计算出左侧和右侧的纬度值。因此红线距
Postgis中Linestring中的点(由osm2pgsql从osm导入)按顺序描述(经度,纬度) 例如慕尼黑 map 中的线串 'LINESTRING(11.4068032 47.8580927
给定左上长/纬度和右下长/纬度,我如何确定给定的长/纬度是否落在矩形内? 理想情况下我会看类似的东西 bool IsWithinArea(float topLeftLat,float topLeftL
几天来,我一直在尝试让纬度/经度检查器、速度计、高度计工作,但似乎没有任何工作。我尝试过使用 Android 的内置 locationmanager 和 google play 服务。现在我回来尝试
我有经纬度形式的位置坐标,例如:23⁰ 39' 24.8"N & 58⁰ 11' 36.5"E,请参见下图。但是在我的工作场所我使用 ArcGIS 并且它似乎不支持度数(纬度,经度)形式的坐标。我现在
网上看了一些教程,发现LocationManager就是这样做的。这是我在网上找到的代码。但是,我不明白。为什么我不能得到长/纬度?为什么要经历所有“改变”位置的事情...... lm=(Locati
我一直在关注此网站的教程:' http://wptrafficanalyzer.in/blog/storing-google-maps-android-api-v2-marker-locations-
我需要使用用户当前的纬度/经度和数据库中存储的一些值进行一些计算。问题是 Location.getLatitude() 返回一个类似 4119778.0 的值,而我在数据库中的值保存为 41.1675
所以在 PostgreSQL 中,我有一堆 long/lat 的几何值,其格式如下: 0101000020E610000095B9F94674CF37C09CBF0985083B5040 所以在 Po
在 GoogleMap 中,有标记的纬度和经度概念。 MySQL 中的 Point 数据类型有两个坐标 x 和 y。我不知道 Point 的坐标代表什么;所以我想知道什么表示 Point 根据 Goo
我是一名优秀的程序员,十分优秀!