1

我正在开发一个小应用程序,它获取当前的地理坐标并使用 json 对象返回相关地址。问题是:如果我在三星 Galaxy S 上运行应用程序,它可以完美运行,但是,如果我在 Galaxy S3 上运行它,则会发生运行时错误,例如,它获取当前位置坐标但无法检索 json 对象。代码如下:

package com.demobasar;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;

import android.os.Bundle;

import android.widget.TextView;
import android.widget.Toast;

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.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MainActivity extends ActionBarActivity implements LocationListener {
    TextView longT, latT, ulke, sehir, ilce, sokak, mahalle;
    private LocationManager locationManager;
    private String provider;
    Location location;
    double lat, lng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        longT = (TextView) findViewById(R.id.longT);
        latT = (TextView) findViewById(R.id.lat);
        ulke = (TextView) findViewById(R.id.ulke);
        sehir = (TextView) findViewById(R.id.sehir);
        ilce = (TextView) findViewById(R.id.ilce);
        sokak = (TextView) findViewById(R.id.sokak);
        mahalle =(TextView) findViewById(R.id.mahalle);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            onLocationChanged(location);
        } else {
            longT.setText("Location not available");
            latT.setText("Location not available");
        }
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                    try {
                        ulke.setText(getJson("http://maps.basarsoft.com.tr/yb5.ashx?f=rg&x=" + lng + "&y=" +lat).getString("Order0"));
                        sehir.setText(getJson("http://maps.basarsoft.com.tr/yb5.ashx?f=rg&x=" + lng + "&y=" +lat).getString("Order1"));
                        ilce.setText(getJson("http://maps.basarsoft.com.tr/yb5.ashx?f=rg&x=" + lng + "&y=" +lat).getString("Order8"));
                        mahalle.setText(getJson("http://maps.basarsoft.com.tr/yb5.ashx?f=rg&x=" + lng + "&y=" +lat).getString("Order9"));
                        sokak.setText(getJson("http://maps.basarsoft.com.tr/yb5.ashx?f=rg&x=" + lng + "&y=" +lat).getString("Street"));
                    } catch (JSONException e) {
                         e.printStackTrace();

                    }

            }
        }, 10000);

    }
    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }
    @Override
    public void onLocationChanged(Location location) {
        lat = location.getLatitude();
        lng = location.getLongitude();
        longT.setText("" + lng);
        latT.setText("" + lat);
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    }
    public static JSONObject getJson(String url){

        InputStream is = null;
        String result = "";
        JSONObject jsonObject = null;

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httppost = new HttpGet(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch(Exception e) {
            return null;
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch(Exception e) {
            return null;
        }
        try {
            jsonObject = new JSONObject(result);
        } catch(JSONException e) {
            return null;
        }
        return jsonObject;
    }
}

android清单如下:

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

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="19" />
        <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL"/>


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.demobasar.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>
    </application>

</manifest>

最后是LogCat:

01-19 22:01:14.689  23948-23948/com.demobasar E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.demobasar.MainActivity$1.run(MainActivity.java:68)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
            at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

1

由于 API 3.0 如果您在 GUI 线程上执行任何网络操作,Android 会抛出 NetworkOnMainThreadException,这就是您在处理程序中所做的(它是在 GUI 线程上创建的,因此它在 GUI 线程上运行)。Galaxy S 带有 Android 2.x,它不会抛出这个异常。

NetworkOnMainThreadException 可能在您的 logcat 中更深的地方

通常的解决方案是将网络操作放入AsyncTask

供参考 http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html

于 2014-01-19T20:16:13.343 回答