[android]获取用户的当前市

发布时间: 2017/3/19 16:43:09
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

嗨我贴出后你的建议我可以感觉到,我解决我的问题变得封闭一前一阵子,关于同一主题的问题。这个应用程序也现在崩溃像我点击 button 与显示器下面的错误消息︰

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:

在条件下 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");
}

如果它还没能找到至少一个 address 你应该考虑空状态显示给用户。

它也似乎像你忘了你纬度和经度之前调用来初始化addresses = geocoder.getFromLocation(lat, lon, 1);

若要正确地初始化这,请执行以下操作︰

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

如果您需要任何更多帮助查阅这来自页 android 。应该支持您需要的所有信息。

编辑︰

我假设你我们进一步在 process ,但似乎你只会试着去 location 的 latLong 位置,你永远也没有获得。要实现获得 address 你将必须首先有用户的齐全。

再次,如上文所述的页面应该解释一切您需要获得 location ,但请确保以下︰

1.有权访问用户的 location (为 Android 6 + 使用运行时权限)

<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 和 ave 你 activity 实现一些回调

回调

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.获得 location 从 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 长期并尝试获得 address ,尝试过。

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();
}

这应该足以获得该设备的实际地址和问 geocoder 的地址。我改变的例子有点简化这个问题。谷歌的示例处理取 address 有点更干净。请注意,你也会有断开 GoogleApi 停止时你 activity 等。再次我推荐阅读整个教程页面。你可以找到他们执行在这个页面上 GitHub en 的示例

官方微信
官方QQ群
31647020