0

当我在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 emulator上运行良好。

布局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>

我是安卓新手。请帮我。

4

1 回答 1

2

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

如何修复 android.os.NetworkOnMainThreadException?

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

于 2013-07-24T19:20:40.003 回答