致命异常:AsyncTask#1 doitbackground

时间:2014-05-25 18:54:04

标签: android json eclipse google-maps android-asynctask

我是初学者在android中并试图让android地图旅行,但我的标记无法显示。因为我的logcat中有一些错误,并且通知:遗憾的是app已经停止工作了。你能帮助我吗? (抱歉我的英语不好)

这是我的主要活动:

package id.meita.redproject;

import id.meita.redproject.entity.hotelpku;
import java.util.ArrayList;
import org.json.JSONObject;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.os.AsyncTask;

public class MainActivity extends FragmentActivity
{
    private GoogleMap       map;
    private JSONHelper      json;
    private ProgressDialog  pDialog;

    private ArrayList<hotelpku> listhotelpku;
    private static String       URL_API = "http://10.0.3.2/api/hotelpku.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        json = new JSONHelper();
        new AsynTaskMain().execute();
        setupMapIfNeeded();
    }
    /**
     * initialize map
     */
    private void setupMapIfNeeded() {
        if (map == null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
                    .findFragmentById(R.id.maps);
            map = supportMapFragment.getMap();

            if (map != null) {
                setupMap();
            }
        }
    }
    /**
     * Setup Map
     */
    private void setupMap()
    {
        map.setMyLocationEnabled(true);
        moveToMyLocation();
    }
        private void moveToMyLocation()
        {
            LocationManager locationManager = (LocationManager)
                    getSystemService(Context.LOCATION_SERVICE);
                    Criteria criteria = new Criteria();

            Location location =
                    locationManager.getLastKnownLocation (locationManager.getBestProvider(criteria,false));
            if (location !=null)
            {
                map.animateCamera(CameraUpdateFactory.newLatLngZoom(
                        new LatLng(location.getLatitude(),
                        location.getLongitude()), 13));
                        }
                         }




                     @Override
                     public boolean onCreateOptionsMenu(Menu menu)
                     {

                     getMenuInflater().inflate(R.menu.main, menu);
                     return true;
                     }

                     @Override
                     protected void onResume()
                     {
                     // TODO Auto-generated method stub
                     super.onResume();

                     int resCode =
                    GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
                     if (resCode != ConnectionResult.SUCCESS)
                    {
                     GooglePlayServicesUtil.getErrorDialog(resCode, this, 1);
                     }
                     }
                     private class AsynTaskMain extends AsyncTask<Void,Void,Void>
                     {

                         protected void onPostExecute(Void result)
                         {
                             pDialog.dismiss();
                             runOnUiThread(new Runnable()
                             {

                                 public void run()
                                 {
                                     for (int i = 0; i < listhotelpku.size(); i++)
                                     {
                                         map.addMarker(new MarkerOptions()
                                         .position (new
                                                 LatLng(listhotelpku.get(i).getLat(),listhotelpku.get(i).getLng()))
                                                 .title(listhotelpku.get(i).getNama())
                                                 .snippet(listhotelpku.get(i).getAlamat()));

                                     }
                                 }
                             });
                                         super.onPostExecute(result);
                         }

                         protected void onPreExecute()
                         {
                             super.onPreExecute();
                             pDialog = new ProgressDialog(MainActivity.this);
                             pDialog.setMessage("Loading....");
                             pDialog.setCancelable(true);
                             pDialog.show();
                         }

                         protected Void doInBackground(Void... params)
                         {
                             JSONObject jObject = json.getJSONFromURL(URL_API);
                             listhotelpku = json.gethotelpkuAll(jObject);
                             return null;
                         }
                     }

                     }

这是JSONHelper类:

package id.meita.redproject;

import id.meita.redproject.entity.hotelpku;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.maps.model.LatLng;
import android.util.Log;

public class JSONHelper
{
    private InputStream     is              = null;
    private JSONObject      jsonObject      = null;
    private String          json            = "";

    private final String    TAG_HOTELPKU    = "hotelpku";
    private final String    TAG_ID          = "id";
    private final String    TAG_NAMA        = "nama";
    private final String    TAG_ALAMAT      = "alamat";
    private final String    TAG_LAT         = "lat";
    private final String    TAG_LNG         = "lng";
    private final String    TAG_ROUTES      = "routes";
    private final String    TAG_LEGS        = "legs";
    private final String    TAG_STEPS       = "steps";
    private final String    TAG_POLYLINE    = "polyline";
    private final String    TAG_POINTS      = "points";
    private final String    TAG_START       = "start_location";
    private final String    TAG_END         = "end_location";

    public JSONObject getJSONFromURL(String url)
    {
        Log.d("TAG","URL Request ->" + url);
        try
        {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);

            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }

            is.close();
            json = sb.toString();
        } catch (Exception e)
        {
            // TODO: handle exception
        }

        try
        {
            jsonObject = new JSONObject(json);


        } catch (JSONException e)
        {
            // TODO: handle exception
        }

        return jsonObject;
    }

    public ArrayList<hotelpku> gethotelpkuAll(JSONObject jobj)
    {
        ArrayList<hotelpku> listhotelpku = new ArrayList<hotelpku>();

        try
        {
            JSONArray arrayhotelpku = jobj.getJSONArray(TAG_HOTELPKU);

            for (int i = 0; i < arrayhotelpku.length(); i++)
            {

                JSONObject jobject = arrayhotelpku.getJSONObject(i);
                Log.d("TAG", "lat : " + jobject.getDouble(TAG_LNG));
                Log.d("log", "muter ke " + i);

                listhotelpku.add(new hotelpku(jobject.getInt(TAG_ID), jobject.getString(TAG_NAMA), jobject
                        .getString(TAG_ALAMAT), jobject
                        .getDouble(TAG_LAT), jobject.getDouble(TAG_LNG)));

            }
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
        return listhotelpku;
    }

    /*
     * Untuk decode Polyline
     * 
     * @params String
     * 
     * @return List<LatLng>
     */
    private List<LatLng> decodePoly(String encoded)
    {
        List<LatLng> poly = new ArrayList<LatLng>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;
        while (index < len)
        {
            int b, shift = 0, result = 0;
            do
            {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;
            shift = 0;
            result = 0;
            do
            {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng position = new LatLng(lat / 1E5, lng / 1E5);
            poly.add(position);
        }
        return poly;

    }

    /*
     * Untuk mendapatkan direction
     * 
     * @params JSONObject
     * 
     * @return List<LatLng>
     */
    public List<LatLng> getDirection(JSONObject jObj)
    {

        List<LatLng> directions = new ArrayList<LatLng>();

        try
        {
            JSONObject objRoute = jObj.getJSONArray(TAG_ROUTES).getJSONObject(0);
            JSONObject objLegs = objRoute.getJSONArray(TAG_LEGS).getJSONObject(0);
            JSONArray arraySteps = objLegs.getJSONArray(TAG_STEPS);
            for (int wi2t = 0; wi2t < arraySteps.length(); wi2t++)
            {
                JSONObject step = arraySteps.getJSONObject(wi2t);
                JSONObject objStart = step.getJSONObject(TAG_START);
                JSONObject objEnd = step.getJSONObject(TAG_END);
                double latStart = objStart.getDouble(TAG_LAT);
                double lngStart = objStart.getDouble(TAG_LNG);

                directions.add(new LatLng(latStart, lngStart));

                JSONObject poly = step.getJSONObject(TAG_POLYLINE);
                String encodedPoly = poly.getString(TAG_POINTS);

                List<LatLng> decodedPoly = decodePoly(encodedPoly);
                for (int eka = 0; eka < decodedPoly.size(); eka++)
                {
                    directions.add(new LatLng(decodedPoly.get(eka).latitude, decodedPoly.get(eka).longitude));
                }

                double latEnd = objEnd.getDouble(TAG_LAT);
                double lngEnd = objEnd.getDouble(TAG_LNG);
                directions.add(new LatLng(latEnd, lngEnd));

            }
        } catch (JSONException e)
        {
            // TODO: handle exception
        }

        return directions;
    }
}

是我的LOGCAT:

05-27 00:08:55.732: E/Trace(1998): error opening trace file: No such file or directory (2)
05-27 00:08:55.872: I/Google Maps Android API(1998): Google Play services client version: 4323000
05-27 00:08:55.884: I/Google Maps Android API(1998): Google Play services package version: 4452070
05-27 00:08:55.896: D/dalvikvm(1998): GC_CONCURRENT freed 171K, 10% free 2573K/2856K, paused 3ms+0ms, total 10ms
05-27 00:08:56.028: D/dalvikvm(1998): GC_CONCURRENT freed 245K, 12% free 2719K/3084K, paused 2ms+1ms, total 11ms
05-27 00:08:56.092: I/fpp(1998): Making Creator dynamically
05-27 00:08:56.092: I/Google Maps Android API(1998): Google Play services client version: 4452000
05-27 00:08:56.128: D/dalvikvm(1998): GC_CONCURRENT freed 246K, 12% free 2857K/3216K, paused 3ms+0ms, total 11ms
05-27 00:08:56.264: D/dalvikvm(1998): GC_CONCURRENT freed 143K, 8% free 3160K/3416K, paused 2ms+0ms, total 17ms
05-27 00:08:56.276: D/dalvikvm(1998): GC_FOR_ALLOC freed <1K, 8% free 3160K/3416K, paused 3ms, total 10ms
05-27 00:08:56.296: I/dalvikvm-heap(1998): Grow heap (frag case) to 4.266MB for 1127532-byte allocation
05-27 00:08:56.308: D/dalvikvm(1998): GC_FOR_ALLOC freed 0K, 6% free 4261K/4520K, paused 9ms, total 9ms
05-27 00:08:56.312: D/dalvikvm(1998): GC_CONCURRENT freed 0K, 6% free 4261K/4520K, paused 2ms+0ms, total 3ms
05-27 00:08:56.344: D/dalvikvm(1998): GC_CONCURRENT freed 66K, 4% free 4730K/4908K, paused 2ms+0ms, total 5ms
05-27 00:08:56.348: D/dalvikvm(1998): GC_FOR_ALLOC freed 6K, 4% free 4724K/4908K, paused 2ms, total 2ms
05-27 00:08:56.356: I/dalvikvm-heap(1998): Grow heap (frag case) to 5.793MB for 1127532-byte allocation
05-27 00:08:56.360: D/dalvikvm(1998): GC_FOR_ALLOC freed <1K, 4% free 5825K/6012K, paused 4ms, total 4ms
05-27 00:08:56.368: D/dalvikvm(1998): GC_CONCURRENT freed 0K, 4% free 5825K/6012K, paused 2ms+3ms, total 7ms
05-27 00:08:56.396: D/TAG(1998): URL Request ->http://10.0.3.2/api/hotelpku.php
05-27 00:08:56.464: D/libEGL(1998): loaded /system/lib/egl/libEGL_emulation.so
05-27 00:08:56.468: D/(1998): HostConnection::get() New Host Connection established 0xb8585340, tid 1998
05-27 00:08:56.480: D/libEGL(1998): loaded /system/lib/egl/libGLESv1_CM_emulation.so
05-27 00:08:56.480: D/libEGL(1998): loaded /system/lib/egl/libGLESv2_emulation.so
05-27 00:08:56.512: W/EGL_emulation(1998): eglSurfaceAttrib not implemented
05-27 00:08:56.524: D/OpenGLRenderer(1998): Enabling debug mode 0
05-27 00:08:56.616: W/EGL_emulation(1998): eglSurfaceAttrib not implemented
05-27 00:08:56.848: D/(1998): HostConnection::get() New Host Connection established 0xb85b9708, tid 2023
05-27 00:08:57.180: I/Choreographer(1998): Skipped 32 frames!  The application may be doing too much work on its main thread.
05-27 00:08:57.808: D/dalvikvm(1998): GC_CONCURRENT freed 907K, 15% free 6076K/7092K, paused 5ms+2ms, total 56ms
05-27 00:08:57.808: D/dalvikvm(1998): WAIT_FOR_CONCURRENT_GC blocked 48ms
05-27 00:08:57.808: D/dalvikvm(1998): WAIT_FOR_CONCURRENT_GC blocked 46ms
05-27 00:08:57.812: W/dalvikvm(1998): threadid=21: thread exiting with uncaught exception (group=0xa6180908)
05-27 00:08:57.812: E/AndroidRuntime(1998): FATAL EXCEPTION: AsyncTask #1
05-27 00:08:57.812: E/AndroidRuntime(1998): java.lang.RuntimeException: An error occured while executing doInBackground()
05-27 00:08:57.812: E/AndroidRuntime(1998):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
05-27 00:08:57.812: E/AndroidRuntime(1998):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
05-27 00:08:57.812: E/AndroidRuntime(1998):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
05-27 00:08:57.812: E/AndroidRuntime(1998):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
05-27 00:08:57.812: E/AndroidRuntime(1998):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-27 00:08:57.812: E/AndroidRuntime(1998):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-27 00:08:57.812: E/AndroidRuntime(1998):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-27 00:08:57.812: E/AndroidRuntime(1998):     at java.lang.Thread.run(Thread.java:856)
05-27 00:08:57.812: E/AndroidRuntime(1998): Caused by: java.lang.NullPointerException
05-27 00:08:57.812: E/AndroidRuntime(1998):     at id.meita.redproject.JSONHelper.gethotelpkuAll(JSONHelper.java:106)
05-27 00:08:57.812: E/AndroidRuntime(1998):     at id.meita.redproject.MainActivity$AsynTaskMain.doInBackground(MainActivity.java:143)
05-27 00:08:57.812: E/AndroidRuntime(1998):     at id.meita.redproject.MainActivity$AsynTaskMain.doInBackground(MainActivity.java:1)
05-27 00:08:57.812: E/AndroidRuntime(1998):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-27 00:08:57.812: E/AndroidRuntime(1998):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
05-27 00:08:57.812: E/AndroidRuntime(1998):     ... 4 more
05-27 00:08:58.052: I/Choreographer(1998): Skipped 51 frames!  The application may be doing too much work on its main thread.
05-27 00:08:58.364: D/dalvikvm(1998): GC_FOR_ALLOC freed 957K, 15% free 6351K/7420K, paused 6ms, total 6ms
05-27 00:08:58.388: D/dalvikvm(1998): GC_CONCURRENT freed 68K, 14% free 6452K/7420K, paused 5ms+1ms, total 18ms
05-27 00:08:58.440: D/dalvikvm(1998): GC_CONCURRENT freed 710K, 11% free 6989K/7832K, paused 2ms+0ms, total 6ms
05-27 00:08:59.232: I/Choreographer(1998): Skipped 67 frames!  The application may be doing too much work on its main thread.
05-27 00:09:00.316: E/WindowManager(1998): Activity id.meita.redproject.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{5330f044 V.E..... R......D 0,0-684,192} that was originally added here
05-27 00:09:00.316: E/WindowManager(1998): android.view.WindowLeaked: Activity id.meita.redproject.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{5330f044 V.E..... R......D 0,0-684,192} that was originally added here
05-27 00:09:00.316: E/WindowManager(1998):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
05-27 00:09:00.316: E/WindowManager(1998):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
05-27 00:09:00.316: E/WindowManager(1998):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
05-27 00:09:00.316: E/WindowManager(1998):  at android.app.Dialog.show(Dialog.java:281)
05-27 00:09:00.316: E/WindowManager(1998):  at id.meita.redproject.MainActivity$AsynTaskMain.onPreExecute(MainActivity.java:137)
05-27 00:09:00.316: E/WindowManager(1998):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
05-27 00:09:00.316: E/WindowManager(1998):  at android.os.AsyncTask.execute(AsyncTask.java:534)
05-27 00:09:00.316: E/WindowManager(1998):  at id.meita.redproject.MainActivity.onCreate(MainActivity.java:40)
05-27 00:09:00.316: E/WindowManager(1998):  at android.app.Activity.performCreate(Activity.java:5104)
05-27 00:09:00.316: E/WindowManager(1998):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-27 00:09:00.316: E/WindowManager(1998):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-27 00:09:00.316: E/WindowManager(1998):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-27 00:09:00.316: E/WindowManager(1998):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-27 00:09:00.316: E/WindowManager(1998):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-27 00:09:00.316: E/WindowManager(1998):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-27 00:09:00.316: E/WindowManager(1998):  at android.os.Looper.loop(Looper.java:137)
05-27 00:09:00.316: E/WindowManager(1998):  at android.app.ActivityThread.main(ActivityThread.java:5041)
05-27 00:09:00.316: E/WindowManager(1998):  at java.lang.reflect.Method.invokeNative(Native Method)
05-27 00:09:00.316: E/WindowManager(1998):  at java.lang.reflect.Method.invoke(Method.java:511)
05-27 00:09:00.316: E/WindowManager(1998):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-27 00:09:00.316: E/WindowManager(1998):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-27 00:09:00.316: E/WindowManager(1998):  at dalvik.system.NativeStart.main(Native Method)
05-27 00:09:01.296: I/Process(1998): Sending signal. PID: 1998 SIG: 9

继承人显示课程:

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

     <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
     <permission
          android:name="id.meita.redproject.permission.MAPS_RECEIVE"
          android:protectionLevel="signature"/>
    <uses-permission android:name="id.meita.redproject.permission.MAPS_RECEIVE"/>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyDmKMij1Moz5C3FRs3s1gqXrVrpXjxKKEQ" />
        <activity
            android:name="id.meita.redproject.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>

1 个答案:

答案 0 :(得分:0)

网络超时导致的错误

05-26 01:36:50.947: W/System.err(1731): Caused by: java.net.ConnectException: failed to connect to /10.0.2.2 (port 80): connect failed: ETIMEDOUT (Connection timed out)

您确定此网址

http://10.0.2.2/api/hotelpku.php

可以通过手机访问吗? [尝试使用移动设备上安装的常规网络浏览器打开它

额外检查:记得在清单文件中添加INTERNET权限。

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