获取用户当前的城市

时间:2017-01-03 14:14:47

标签: java android android-studio geolocation

您好我刚刚发布了一个关于同一主题的问题,在听完您的建议后,我可以感觉到我已经关闭解决问题了。当我点击监视器中显示以下错误消息的按钮时,应用程序现在崩溃了:

FATAL EXCEPTION: main

Process: com.example.apple.myapp1, PID: 10081
                                       java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
                                           at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
                                           at java.util.ArrayList.get(ArrayList.java:308)
                                           at com.example.apple.myapp1.MainActivity$1.onClick(MainActivity.java:62)

MainActivity.java

package com.example.apple.myapp1;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {
double lats, lons;
Geocoder geocoder;
double lat = lats;
double lon = lons;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btnGetLocation = (Button) findViewById(R.id.button1);
    btnGetLocation.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            ProgressDialog mProgressDialog = new         ProgressDialog(MainActivity.this);
            mProgressDialog.setMessage("Fetching location...");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.show();
            geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
            List<Address> addresses = null;
            try {
                addresses = geocoder.getFromLocation(lat, lon, 1);
            } catch (IOException e) {

                e.printStackTrace();
            }

            if (addresses != null) {
                String address = addresses.get(0).getAddressLine(0);
                String city = addresses.get(0).getLocality();
                String state = addresses.get(0).getAdminArea();
                String country = addresses.get(0).getCountryName();
                String postalCode = addresses.get(0).getPostalCode();
                String knownName = addresses.get(0).getFeatureName();

                mProgressDialog.dismiss();
                TextView cellText = (TextView)     findViewById(R.id.cellText);
                cellText.setText(address);

            } else {
                mProgressDialog.dismiss();
                TextView cellText = (TextView) findViewById(R.id.cellText);
                cellText.setText("Error");
            }
        }
    });
}
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Please click the button below to get your location" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click Me" />

<TextView
    android:id="@+id/cellText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />

<TextView
    android:id="@+id/lacationText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />


</LinearLayout>

1 个答案:

答案 0 :(得分:0)

在条件if (addresses != null) { }中,您还应该检查地址的长度,因为可能有0。

if (addresses != null && addresses.size() > 0) {
    String address = addresses.get(0).getAddressLine(0);
    String city = addresses.get(0).getLocality();
    String state = addresses.get(0).getAdminArea();
    String country = addresses.get(0).getCountryName();
    String postalCode = addresses.get(0).getPostalCode();
    String knownName = addresses.get(0).getFeatureName();

    mProgressDialog.dismiss();
    TextView cellText = (TextView) findViewById(R.id.cellText);
    cellText.setText(address);

} else {
    mProgressDialog.dismiss();
    TextView cellText = (TextView) findViewById(R.id.cellText);
    cellText.setText("Error");
}

如果无法找到至少一个地址,则应考虑向用户显示空状态。

在调用addresses = geocoder.getFromLocation(lat, lon, 1);

之前,您似乎忘了初始化纬度和经度

要正确初始化,请执行以下操作:

Location location = intent.getParcelableExtra(__YOUR_PACKAGE_NAME__ + ".LOCATION_DATA_EXTRA");
lat = location.getLatitude();
lon = location.getLongitude();

如果您需要更多帮助,请查看此page from android。它应该包含您需要的所有信息。

编辑:

我有点假设你我们在这个过程中更进一步,但似乎你只是试图获得一个你从未获得的latLong位置的位置。要获得地址,您必须先拥有用户的lcoation。

同样,上面提到的页面应该解释获取位置所需的一切,但请确保以下内容:

<强> 1。获得访问用户位置的权限(适用于Android 6+使用Runtime permissions

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.gms.location.sample.locationupdates" >

  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</manifest>

<强> 2。获取GoogleApi的实例,并将您的活动实施一些回调

对于回调

public class YourActivity extends AppCompatActivity implements
        ConnectionCallbacks, OnConnectionFailedListener

然后在OnCreate()中创建一个GoogleApiClient实例。

protected GoogleApiClient mGoogleApiClient;

public void onCreate(Bundle savedInstanceState) {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

第3。从GoogleApiClient获取位置 通过正确实现回调来做到这一点。

/**
 * Represents a geographical location.
 */
protected Location mLastLocation;

@Override
public void onConnected(Bundle connectionHint) {
     // Gets the best and most recent location currently available, which may be null
     // in rare cases when a location is not available.
     mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
     if (mLastLocation != null) {
         // Determine whether a Geocoder is available.
         if (!Geocoder.isPresent()) {
             Toast.makeText(this, "no geocoder available", Toast.LENGTH_LONG).show();
             return;
         }
     }
 }

<强> 4。现在获取lat long并尝试获取之前尝试的地址。

lat = mLastLocation.getLatitude();
lon = mLastLocation.getLongitude();

geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
    addresses = geocoder.getFromLocation(lat, lon, 1);
} catch (IOException e) {
    e.printStackTrace();
}

这应该足以获得设备的实际地址并向地理编码器询问地址。为了简化这个问题,我稍微修改了一下这个例子。谷歌的例子处理地址更加干净。请注意,在停止活动等时,您还必须断开Goog​​leApi的连接。我再次建议阅读整个Tutorial page。您可以找到其实施示例on this page on GitHub

相关问题