IntentService类出错

时间:2012-04-20 09:52:05

标签: android service httpclient

我有一个IntentService类,它从服务器解析JSON文件并将属性保存到SQLite数据库中。 但每当我启动它时,应用程序崩溃,并且堆栈跟踪显示错误。 任何人都可以帮我解决错误吗? 感谢

这是我的班级:

public class DBSync extends IntentService {

    //holds new Location[] temporarily, well be released after storing data to DB
    public static VideoLocation[] videoLocations = null;

    private static VideoLocationReceiver receiver = null;

    public DBSync() {
        super("DBSync");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        VideoLocationList locations = null;
        videoLocations = null;

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(
                "http://historyvision.solutions.smfhq.com/api/locations.json");
        try {
            HttpResponse response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                InputStream instream = response.getEntity().getContent();
                BufferedReader r = new BufferedReader(new InputStreamReader(
                        instream, "UTF-8"), 8000);
                StringBuilder total = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    total.append(line);
                }
                instream.close();

                //parse to gson here
                String JSON_Result = total.toString();

                JSON_Result = "{ locations:"+JSON_Result+"}";

                Log.d("DBSync", "JSON_Result:"+JSON_Result);
                Gson gson = new Gson();
                locations = (VideoLocationList)gson.fromJson(JSON_Result, VideoLocationList.class);

                VideoLocationItem[] vidLocItems = locations.getVideoLocations();
                int numLocations = vidLocItems.length;

                videoLocations = new VideoLocation[numLocations];
                for(int i=0; i<vidLocItems.length; i++ ){
                    videoLocations[i] = vidLocItems[i].location;
                }
                if (receiver!=null) {
                    receiver.receivedVideoLocationData(videoLocations);
                }
//              Log.d("DBSync", "resulting json: "+gson.toJson(locations, VideoLocationList.class));
            }
        } catch (ClientProtocolException e) {
            // TODO HANDLE THIS EXCEPTION, E.G. CHECK NETWORK/INFORM USER ETC.
            receiver.receivedVideoLocationData(null);
            e.printStackTrace();
        } catch (IOException e) {
            // TODO HANDLE THIS EXCEPTION, E.G. CHECK NETWORK/INFORM USER ETC.
            e.printStackTrace();
        }

        //only after sucessfully retrieving the remote json we open and update the db
        if (videoLocations != null) {

            JsonDB dbhelper = WWHApplication.getInstance().getJsonDBInstance();
            SQLiteDatabase db = dbhelper.getWritableDatabase();

            //begin transaction for insert
            db.beginTransaction();
            dbhelper.InsertLocationArray(db,videoLocations);
            db.setTransactionSuccessful();//end transaction
            db.endTransaction();
        }

        //fetch db content just for debugging

        JsonDB dbhelper = WWHApplication.getInstance().getJsonDBInstance();
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        VideoLocation[] dbLocations = dbhelper.getVideoLocations(db);
        Gson gs = new Gson();
        for(VideoLocation vl : dbLocations){
            Log.d("DBSync", gs.toJson(vl));
        }
    }

    public static VideoLocation[] getVideoLocations(){
        return videoLocations;
    }


    public static void setVideoLocationReceiver(VideoLocationReceiver vr){
        receiver = vr;
    }

    public interface VideoLocationReceiver {

        public void receivedVideoLocationData(final VideoLocation[] vidLocs);
    }
}

这是堆栈跟踪:

04-20 11:20:32.960: W/System.err(2732): java.net.UnknownHostException: historyvision.solutions.smfhq.com
    04-20 11:20:32.960: W/System.err(2732):     at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
    04-20 11:20:32.960: W/System.err(2732):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
    04-20 11:20:32.960: W/System.err(2732):     at java.net.InetAddress.getAllByName(InetAddress.java:256)
    04-20 11:20:32.960: W/System.err(2732):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
    04-20 11:20:32.960: W/System.err(2732):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
    04-20 11:20:32.960: W/System.err(2732):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
    04-20 11:20:32.960: W/System.err(2732):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
    04-20 11:20:32.960: W/System.err(2732):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
    04-20 11:20:32.960: W/System.err(2732):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
    04-20 11:20:32.960: W/System.err(2732):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
    04-20 11:20:32.960: W/System.err(2732):     at com.wwh.Sync.DBSync.onHandleIntent(DBSync.java:49)
    04-20 11:20:32.960: W/System.err(2732):     at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
    04-20 11:20:32.960: W/System.err(2732):     at android.os.Handler.dispatchMessage(Handler.java:99)
    04-20 11:20:32.960: W/System.err(2732):     at android.os.Looper.loop(Looper.java:130)
    04-20 11:20:32.960: W/System.err(2732):     at android.os.HandlerThread.run(HandlerThread.java:60)
    04-20 11:20:33.040: W/dalvikvm(2732): threadid=9: thread exiting with uncaught exception (group=0x40015560)
    04-20 11:20:33.040: E/AndroidRuntime(2732): FATAL EXCEPTION: IntentService[DBSync]
    04-20 11:20:33.040: E/AndroidRuntime(2732): java.lang.NullPointerException
    04-20 11:20:33.040: E/AndroidRuntime(2732):     at com.wwh.Sync.DBSync.onHandleIntent(DBSync.java:110)
    04-20 11:20:33.040: E/AndroidRuntime(2732):     at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
    04-20 11:20:33.040: E/AndroidRuntime(2732):     at android.os.Handler.dispatchMessage(Handler.java:99)
    04-20 11:20:33.040: E/AndroidRuntime(2732):     at android.os.Looper.loop(Looper.java:130)
    04-20 11:20:33.040: E/AndroidRuntime(2732):     at android.os.HandlerThread.run(HandlerThread.java:60)

stacktrace显示以下行的错误: for(VideoLocation vl:dbLocations){

3 个答案:

答案 0 :(得分:1)

由于未知的主机异常。您可以通过两种方式解决它:

  1. 重新启动模拟器或设备以刷新其DNS缓存
  2. 将另一个异常捕获器添加到UnknownHostException的Try / catch块。更优选的是,我建议您添加一般Exception捕获
  3. 例如:

    ...
    ...
    catch (UnknownHostExceptione) {
          Log.e("test", "unknown host connection error");
    }
    catch (Exception) {
          Log.e("test", "an error occurred: " + e.toString());
    }
    

答案 1 :(得分:0)

检查你的互联网连接,网址,mainfest.xml(你有从那里获得互联网的许可)。错误表明您在调用Web服务时遇到问题,而不是存储在sqlite中。问题在这里,

http://historyvision.solutions.smfhq.com/api/locations.json

答案 2 :(得分:0)

确保在manifest.xml中声明网络权限

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