套接字关闭 - 从API下载

时间:2013-02-25 14:33:33

标签: android android-asynctask

我正在做的是每隔X秒下载一个带AsyncTask的文件列表:

首先获取视频和图像列表,然后下载每个视频和图像。一切都很完美。

package com.example.tvrplayer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class updateFiles extends AsyncTask<Object, Integer, Long> {

     public PlayerActivity activity;

     public updateFiles(PlayerActivity a) { activity = a;}



    @Override
    protected Long doInBackground(Object... params) {
        Context context = (Context) params[0];
        String username = (String) params[1];
        String linkid = (String) params[2];
        String apiurl = (String) params[3];

        JSONArray programs = Json.getJson(apiurl + "/rest/program/device/"+ linkid +"/"+ username +"/"+ activity.deviceid, "GET");
        File mediadir = context.getDir("tvr", Context.MODE_PRIVATE);
            try {
                LINE 44- for (int j=0; j < programs.length(); j++) { 

                    JSONObject json_data = programs.getJSONObject(j);
                    String name = json_data.getString("Name").toLowerCase();
                    name = name.replace("-", "_");
                    if (name.contains("mp4") || name.contains("m4v") || name.contains("png") || name.contains("jpg") || name.contains("jpeg")) {
                        String _name = name.replace("/", "");
                        File file = new File(mediadir, _name);
                        Log.i("FILE SIZE", ""+file.length());
                        if ( file.length() > 0 ) {
                            Log.i("FILE EXISTS", _name);
                        } else {
                            Log.i("START DOWNLOAD", _name);
                            new Download().execute(context, _name, apiurl + "/rest/transfer/"+ linkid +"/"+ username +"/" + json_data.getString("ID"));
                        }
                        Log.i("FILES found", ""+mediadir.listFiles().length);
                    }
                }
        } catch (JSONException e) {
            Log.e("JSON Exception", e.getMessage());
            e.printStackTrace();
        }
//      activity.filelist = mediadir.listFiles();
        return null;
    }

    @Override
    protected void onPostExecute(Long result) {}

}

过了一会儿我收到了这个错误:

02-25 16:19:19.578: E/JSON - 2 -(17470): java.net.SocketException: Socket closed - http://192.168.2.136:8080/rest/program/device/123someasdidFoo123123/email@foo.com/000

02-25 16:19:16.648: W/dalvikvm(17284): threadid=11: thread exiting with uncaught exception (group=0x40bf11f8)
02-25 16:19:16.664: E/AndroidRuntime(17284): FATAL EXCEPTION: AsyncTask #1
02-25 16:19:16.664: E/AndroidRuntime(17284): java.lang.RuntimeException: An error occured while executing doInBackground()
02-25 16:19:16.664: E/AndroidRuntime(17284):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
02-25 16:19:16.664: E/AndroidRuntime(17284):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
02-25 16:19:16.664: E/AndroidRuntime(17284):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
02-25 16:19:16.664: E/AndroidRuntime(17284):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
02-25 16:19:16.664: E/AndroidRuntime(17284):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
02-25 16:19:16.664: E/AndroidRuntime(17284):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
02-25 16:19:16.664: E/AndroidRuntime(17284):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
02-25 16:19:16.664: E/AndroidRuntime(17284):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
02-25 16:19:16.664: E/AndroidRuntime(17284):    at java.lang.Thread.run(Thread.java:856)
02-25 16:19:16.664: E/AndroidRuntime(17284): Caused by: java.lang.NullPointerException
02-25 16:19:16.664: E/AndroidRuntime(17284):    at com.example.tvrplayer.updateFiles.doInBackground(updateFiles.java:44)
02-25 16:19:16.664: E/AndroidRuntime(17284):    at com.example.tvrplayer.updateFiles.doInBackground(updateFiles.java:1)
02-25 16:19:16.664: E/AndroidRuntime(17284):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
02-25 16:19:16.664: E/AndroidRuntime(17284):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-25 16:19:16.664: E/AndroidRuntime(17284):    ... 5 more

这是从API获取内容的JSON文件

package com.example.tvrplayer;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
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 android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class Json {

    static JSONArray getJson(String url, String method) {
        // Log.i("JSON",url);

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

        // HTTP
        try {
            HttpClient httpclient = new DefaultHttpClient(); // for port 80 requests!
            if ( method == "GET") {
                HttpGet httpget = new HttpGet(url);
                HttpResponse response = httpclient.execute(httpget);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                if (entity != null) {
                    httpget.abort();
                }
            } else if (method == "POST") {
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }



        } catch(Exception e) {
            Log.e("JSON - 1 -", e.toString());
            return null;
        }

        // Read response to string
        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();    
//          Log.d("JSON result",result);
        } catch(Exception e) {
            Log.e("JSON - 2 -", e.toString() + " - " + url);
            return null;
        }

        // Convert string to object
        try {
            jsonObject = new JSONArray(result);            
        } catch(JSONException e) {
            try {
                jsonObject = new JSONArray("["+result+"]");            
            } catch(JSONException e1) {
                Log.e("JSON - 3 -", e1.toString());
                return null;
            }
        }

        return jsonObject;
    }
}

所以我想象的是,当asynctask正忙着下载另一个下载完成并关闭连接?

任何想法是什么或如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您在Null Pointer Exception方法的第44行获得doBackground()。请发布完整的代码,以便我们为您提供进一步的帮助。确保在使用任何对象之前完成所有初始化。在任何情况下,检查第44行,无论你在那里使用哪个对象,都要确保它不是NULL。