当我通过谷歌地图使用地理编码请求地址时,应用程序崩溃

时间:2013-07-24 19:17:57

标签: android api google-maps maps geocoding

当我在 GoogleAPIs模拟器上使用下面的代码时,它工作正常,但是当我使用代码在 Galaxy Nexus模拟器上运行时,它会崩溃,同样的事情发生在我的身上电话,为什么?我需要得到这个代码吗?请指导我。 上课:

import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
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 ="";

 double lat=0;
  double lng=0;
@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) {

    if(!ET1.getText().toString().isEmpty() && !ET2.getText().toString().isEmpty())
    {

        lng=Double.parseDouble(ET1.getText().toString());
        lat=Double.parseDouble(ET2.getText().toString());
            if(this.isOnline())
            {

                JSONObject ret = getLocationInfo(); 
                JSONObject location;
                String location_string="";
                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();

                }
                TV1.setText(" "+location_string);
            }
            else
                TV1.setText("no internet connection");

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



}

public boolean isOnline() {
    // this method works fine(no problems)
        }


public JSONObject getLocationInfo() {

    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) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jsonObject;
 }

}

注意:方法getLocationInfo()适用于 GoogleAPIs模拟器

布局location_name.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TableRow
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Longitude"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/ET1_location_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
         >

        <requestFocus />
    </EditText>

</TableRow>



    <TableRow
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="  Latitude"
        android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/ET2_location_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
             />

    </TableRow>

     <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        >

        <Button
            android:id="@+id/B1_Location_name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Get Location Name" />

    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/TV1_Location_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Location Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    </TableRow>



</LinearLayout>

manifest.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hellp1_package"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="10"
    android:targetSdkVersion="14" />

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



<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

             <activity
        android:name="com.example.hellp1_package.MainActivity"
       android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="/////"></activity>
    <activity android:name="///////"></activity>
    <activity android:name="//////"></activity>
    <activity android:name="///////"></activity>
    <activity android:name="Get_Location_Name"></activity>
</application>

</manifest>

我刚接触到android。请帮帮我。

1 个答案:

答案 0 :(得分:2)

您的函数getLocationInfo(...)正在UI线程上进行http通信。 Android不允许在UI线程上进行网络通信。 Android提供了一个名为AsyncTask的类(请参阅documentaion:http://developer.android.com/reference/android/os/AsyncTask.html),该类用于此类交互。请参阅此链接以获取详细信息和解决方案的一个选项(这可能是您想要的):

How to fix android.os.NetworkOnMainThreadException?

或者您也可以创建一个自定义类来扩展Thread或实现使用Handler发布到UI线程的Runnable