Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/188.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 地图V2上地理编码器的NullPointerException-Android_Java_Android_Google Maps_Nullpointerexception_Google Maps Android Api 2 - Fatal编程技术网

Java 地图V2上地理编码器的NullPointerException-Android

Java 地图V2上地理编码器的NullPointerException-Android,java,android,google-maps,nullpointerexception,google-maps-android-api-2,Java,Android,Google Maps,Nullpointerexception,Google Maps Android Api 2,我是一个新的android开发者,我正在尝试做一个应用程序,使用谷歌地图来获取当前的城市。我正在使用此方法获取城市: public String getLocal(double latitude, double longitude) { String cidade = ""; Geocoder gcd = new Geocoder(this.getApplicationContext(), Locale.getDefault()); List<Address&g

我是一个新的android开发者,我正在尝试做一个应用程序,使用谷歌地图来获取当前的城市。我正在使用此方法获取城市:

public String getLocal(double latitude, double longitude)  {

    String cidade = "";
    Geocoder gcd = new Geocoder(this.getApplicationContext(), Locale.getDefault());
    List<Address> addresses = null;
    try {
         addresses = gcd.getFromLocation(latitude, longitude, 3);
    } catch (IOException e) {
        e.printStackTrace();
    }


    cidade = addresses.get(0).getLocality();

    return cidade;
}
公共字符串getLocal(双纬度、双经度){
字符串cidade=“”;
Geocoder gcd=新的Geocoder(this.getApplicationContext(),Locale.getDefault());
列表地址=空;
试一试{
地址=gcd.getFromLocation(纬度,经度,3);
}捕获(IOE异常){
e、 printStackTrace();
}
cidade=addresses.get(0.getLocation();
返回cidade;
}
有时他会工作,有时当一个用户改变GPS模式时,比如:“仅限设备”,应用程序就会崩溃。有人能帮我吗?
非常感谢

如果您想获取移动设备上的当前位置,请使用此代码获取使用移动网络的地点的海拔高度和高度

gpslocator.java

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;

import com.google.android.gms.location.LocationClient;


import android.app.Activity;

import android.location.Address;

import android.location.Geocoder;

import android.location.Location;

import android.os.Bundle;

import android.util.Log;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

import android.widget.Toast;


public class GPSLOCATOR extends Activity implements ConnectionCallbacks,

OnConnectionFailedListener {

LocationClient mLocationClient;
private TextView addressLabel;
private TextView locationLabel;
private Button getlocationbtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gpslocator);

    locationLabel = (TextView) findViewById(R.id.textView1);
    addressLabel = (TextView) findViewById(R.id.textView2);
    getlocationbtn =(Button) findViewById(R.id.button1);

    mLocationClient = new LocationClient(this, this , this );

    getlocationbtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            //mconnection
        Location currentLocation = mLocationClient.getLastLocation();
        String msg = "Current Location :"+Double.toString(currentLocation.getLatitude())+" , "+ Double.toString(currentLocation.getLongitude());

        locationLabel.setText(msg);

        Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault());

        List<Address> addresses = null;
        try { 
            addresses = geocoder.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);

        }catch(IOException e1) {
            Log.e("loctionsampleActivity","IO Exception in getFromLocation()");
            e1.printStackTrace();
        }
        catch(IllegalArgumentException e2) {
            String errorstring = "Illegal arguments"+Double.toString(currentLocation.getLatitude())+" , "+ Double.toString(currentLocation.getLongitude())+"passed to the address";
            Log.e("LocationSampleActivity", errorstring);
            e2.printStackTrace();
        }

        if(addresses!=null&& addresses.size()>0){
            Address address= addresses.get(0);

            String addressText = String.format("%s, %s,%s",
                    address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0)   :       " ",address.getLocality(),address.getCountryName());

            addressLabel.setText(addressText);
        }
        }
        });
    }
    @Override
    protected void onStart() {
        super.onStart();
        mLocationClient.connect();
        locationLabel.setText("connected....");

    }
    @Override
    public void onConnected (Bundle arg0) {

        Toast.makeText(this, "connection connected", Toast.LENGTH_SHORT).show();

    }
    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        // TODO Auto-generated method stub

        Toast.makeText(this, "conection failed", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub
        Toast.makeText(this, "connection disconnected", Toast.LENGTH_SHORT).show();
    }
}
import java.io.IOException;
导入java.util.List;
导入java.util.Locale;
导入com.google.android.gms.common.ConnectionResult;
导入com.google.android.gms.common.GooglePlayServicesClient;
导入com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
导入com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
导入com.google.android.gms.location.LocationClient;
导入android.app.Activity;
导入android.location.Address;
导入android.location.Geocoder;
导入android.location.location;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.view;
导入android.widget.Button;
导入android.widget.TextView;
导入android.widget.Toast;
公共类GPSLOCATOR扩展活动实现ConnectionCallbacks,
OnConnectionFailedListener{
地点客户M地点客户;
私有文本视图地址标签;
私有文本视图位置标签;
私人按钮getlocationbtn;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\gpslocator);
locationLabel=(TextView)findViewById(R.id.textView1);
addressLabel=(TextView)findViewById(R.id.textView2);
getlocationbtn=(按钮)findViewById(R.id.button1);
mLocationClient=新位置客户端(这个,这个,这个);
getlocationbtn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
//TODO自动生成的方法存根
//M连接
Location currentLocation=mlLocationClient.getLastLocation();
String msg=“当前位置:”+Double.toString(currentLocation.getLatitude())+”,“+Double.toString(currentLocation.getLatitude());
locationLabel.setText(msg);
Geocoder Geocoder=新的Geocoder(getApplicationContext(),Locale.getDefault());
列表地址=空;
试试{
addresses=geocoder.getFromLocation(currentLocation.getLatitude(),currentLocation.getLatitude(),1);
}捕获(IOE1异常){
Log.e(“LocationSampleActivity”,“getFromLocation()中的IO异常”);
e1.printStackTrace();
}
捕获(IllegalArgumentException e2){
String errorstring=“非法参数”+Double.toString(currentLocation.getLatitude())+”,“+Double.toString(currentLocation.getLatitude())+”传递到地址;
Log.e(“LocationSampleActivity”,errorstring);
e2.printStackTrace();
}
if(addresses!=null&&addresses.size()>0){
地址=地址。获取(0);
String addressText=String.format(“%s,%s,%s”,
address.getMaxAddressLineIndex()>0?address.getAddressLine(0):“”,address.GetLocation(),address.getCountryName());
addressLabel.setText(addressText);
}
}
});
}
@凌驾
受保护的void onStart(){
super.onStart();
mLocationClient.connect();
locationLabel.setText(“已连接…”);
}
@凌驾
未连接的公共空间(捆绑arg0){
Toast.makeText(此“连接已连接”,Toast.LENGTH_SHORT).show();
}
@凌驾
连接失败的公共void(连接结果arg0){
//TODO自动生成的方法存根
Toast.makeText(此“连接失败”,Toast.LENGTH_SHORT).show();
}
@凌驾
公共空间已断开连接(){
//TODO自动生成的方法存根
Toast.makeText(此“连接断开”,Toast.LENGTH_SHORT).show();
}
}
gpslocator.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"

    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="get location" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="location " />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="address" />



</LinearLayout>
 <uses-permission android:name = "android.permission.ACCESS_COARSE_LOCATION"/>
 <uses-permission android:name = "android.permission.INTERNET"/>

Mainfest中使用此权限

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"

    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="get location" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="location " />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="address" />



</LinearLayout>
 <uses-permission android:name = "android.permission.ACCESS_COARSE_LOCATION"/>
 <uses-permission android:name = "android.permission.INTERNET"/>

当数据连接打开时,地址文本字段中将显示城市地址


希望这能帮助你……)

来自以下文件:

返回

地址对象的列表。如果未找到匹配项或没有可用的后端服务,则返回null或空列表

这意味着您不能直接调用addresses.get(0).getLocality()。
您必须首先确保
地址!=null
,并且该
地址.size()>0

当您遇到此异常时,是否尝试使用e.printStackTrace()打印它?NPE将出现在哪一行?看起来可能在地址上。是否获取(0)?你在用安卓工作室吗?您应该考虑在取消引用可能为空的内容的所有位置使用注释(Java 8和Swift有防止这些情况的选项)。您是否尝试过使用
Logcat
了解详细信息?我的问题是在LocationManager,我使用时没有尝试/捕获。谢谢大家!:)你好我添加了此测试,但错误仍在继续。仅当我从“仅设备”更改为“高精度模式”时(通过某种方式可以从