简体   繁体   English

Galaxy S3 JSON错误

[英]Galaxy S3 JSON Error

I'm working on an little app, that gets the current geo coordinates and returns the relevant address with json objects. 我正在开发一个小应用程序,该应用程序获取当前的地理坐标并返回带有json对象的相关地址。 Here is the problem: If I run app on Samsung Galaxy S, it works perfectly, however, if I run it on Galaxy S3, there happens a run time error, such that, it gets the current location coordinates but cannot retrieve json object. 问题出在这里:如果我在Samsung Galaxy S上运行应用程序,则可以完美运行,但是,如果我在Galaxy S3上运行该应用程序,则会发生运行时错误,例如,它将获取当前位置坐标,但无法检索json对象。 The code is as following: 代码如下:

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

And android manifest is as follows: 而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>

Finally LogCat: 最后是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)

Since API 3.0 Android is throwing NetworkOnMainThreadException if you do any network stuff on GUI thread, and this is what you are doing in your handler (it was created on GUI thread so it runs on GUI thread). 由于API 3.0如果在GUI线程上进行任何网络操作,Android都会引发NetworkOnMainThreadException,这就是您在处理程序中所做的事情(它是在GUI线程上创建的,因此它在GUI线程上运行)。 Galaxy S comes with Android 2.x, which does not throw this exception. Galaxy S随附Android 2.x,不会引发此异常。

NetworkOnMainThreadException is probably somewhere deeper in your logcat NetworkOnMainThreadException可能在您的logcat中更深的地方

the usual solution is to put network operation into AsyncTask 通常的解决方案是将网络操作放入AsyncTask

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM