0

電話で次のコードを使用して住所 {国、通り、都市} を取得しましたが、多くの入力に対して機能しませんでした。なぜですか? そして時々クラッシュします。利用可能なすべての住所をこの経度と緯度に返すメソッドに経度と緯度を渡して、完全な住所を取得する方法を教えてください。最良の結果を得るための答えを教えてください。助けて。

 import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener; 
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Get_Location_Name extends Activity implements OnClickListener {
private EditText ET1;
private EditText ET2;
private TextView TV1;
private Button B1;
static String result ="";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setContentView(R.layout.location_name);
    ET1=(EditText)this.findViewById(R.id.ET1_location_name);
    ET2=(EditText)this.findViewById(R.id.ET2_location_name);
    TV1=(TextView)this.findViewById(R.id.TV1_Location_name);
    B1=(Button)this.findViewById(R.id.B1_Location_name);
    B1.setOnClickListener(this);
}

@Override
public void onClick(View arg0) {

    String s=null;
    if(!ET1.getText().toString().isEmpty() && !ET2.getText().toString().isEmpty())
    {
            if(this.isOnline())
            {

                for(int i=0;i<=10;i++)
                {
                    s=getAddressFromLocation(Double.parseDouble(ET2.getText().toString()),
                    Double.parseDouble(ET1.getText().toString()),this);
                }
            if(s!=null)
                {
                Log.d("ssss","s"+s);
                TV1.setText(s);
                }
            else
                TV1.setText("s is null");
            }
            else
                TV1.setText("no internet connection");

    }
    else
        TV1.setText("Enter the Lat. and Lon.");



}

public boolean isOnline() {
   // code to check connectivity // it works fine(no problems)
}

ここに私が変更したい方法があります

public static String getAddressFromLocation(final double lon,final double lat, final Context context) 
{

      Thread thread = new Thread() {
   @Override public void run() 
    {

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

       try {
           List<Address> list = geocoder.getFromLocation(
                   lat, lon, 1);
           if (list != null && list.size() > 0) 
               {
               Address address = list.get(0);
               result = " "+address.getAddressLine(0) + ", " + address.getLocality()+","+address.getCountryName();
                   }
           } 
        catch (IOException e)
           {
           Log.e("fafvsafagag", "Impossible to connect to Geocoder", e);
           } 
    }
 };
 thread.start();
 return result;
  }

  }

私の質問に答えてください。

4

1 に答える 1

1

Geocoder が常に値を返すとは限らないという既知の問題があります。Geocoder が常に値を返すとは限らず、 geocoder.getFromLocationName が null のみを返すことを確認してください。for ループで 3 回リクエストを送信できます。少なくとも一度は戻ることができるはずです。そうでない場合は、接続の問題か、サーバーがリクエストに応答しなかったなどの他の問題である可能性があります。私にとっては、インターネットに接続されていても何も返されないことがありました。次に、このより信頼性の高い方法を使用して、毎回アドレスを取得しました。

//lat, lng are Double variables  containing latitude and longitude values. 
public JSONObject getLocationInfo() {
        //Http Request
        HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {
            } catch (IOException e) {
        }
                //Create a JSON from the String that was return.
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

完全なアドレスを取得するために、次のように関数を呼び出しました。

JSONObject ret = getLocationInfo(); //Get the JSON that is returned from the API call
JSONObject location;
String location_string;
//Parse to get the value corresponding to `formatted_address` key. 
try {
    location = ret.getJSONArray("results").getJSONObject(0);
    location_string = location.getString("formatted_address");
    Log.d("test", "formattted address:" + location_string);
} catch (JSONException e1) {
    e1.printStackTrace();

}

これは内部AsyncTaskまたは新しいスレッドで呼び出すことができます。私Asynctaskは同じために使用しました。これが役に立てば幸いです。これは私にとってはうまくいきました。URL を緯度と経度の座標に置き換えると、返された JSON オブジェクトが Web ブラウザーに表示されます。何が起こったのかがわかります。

于 2013-07-23T19:58:29.827 に答える