AsyncTask doInBackground ForceClose有时候

时间:2012-03-02 16:08:28

标签: android

我正试图在我的程序中压缩所有力量关闭,这是经常出现的一个:

java.lang.RuntimeException: An error occured while executing doInBackground()
android.os.AsyncTask$3.done(AsyncTask.java:200)
java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
java.util.concurrent.FutureTask.setException(FutureTask.java:124)
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
java.util.concurrent.FutureTask.run(FutureTask.java:137)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
java.lang.Thread.run(Thread.java:1096) Caused by: java.lang.NullPointerException
org.json.JSONTokener.more(JSONTokener.java:98)
org.json.JSONTokener.next(JSONTokener.java:108)
org.json.JSONTokener.nextClean(JSONTokener.java:162)
org.json.JSONArray.(JSONArray.java:103)
org.json.JSONArray.(JSONArray.java:150)
com.appinfluence.musicpromotion.SongList$LoadList.doInBackground(SongList.java:969)
com.appinfluence.musicpromotion.SongList$LoadList.doInBackground(SongList.java:1)
android.os.AsyncTask$2.call(AsyncTask.java:185)
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

这是正在运行的AsyncTask

private class LoadList extends AsyncTask<String, UserRecord, JSONArray> {

    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    String[] displayname = null;
    String[] song_id = null;
    String[] song_name = null;
    String[] artist = null;
    String[] description = null;
    String[] genre = null;
    String[] custom_genre = null;
    String[] album = null;
    String[] timestamp = null;
    String[] avatar = null;
    String[] section = null;
    String[] plays = null;
    String[] downloads = null;
    String[] ratingcount = null;
    String[] commentcount = null;
    int[] dlFlag = null;
    JSONArray jArray;
    Float[] test_rating;
    String[] songurl;
    UserRecord user5;
    String[] viewss;    
    String[] link1;
    String[] link2;
    String[] link3;
    String[] link4;
    String[] link5;



    protected JSONArray doInBackground(String... link) {

        linkurl = link[0];
        URI uri = null;
        try {
            uri = new URI(link[0]);
        } catch (URISyntaxException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }

        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(uri);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection"+e.toString());
        }

        //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line="0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }

        try{
            jArray = new JSONArray(result);
            JSONObject json_data=null;

            displayname = new String[jArray.length()];
            song_name = new String[jArray.length()];
            artist = new String[jArray.length()];
            description = new String[jArray.length()];
            genre = new String[jArray.length()];
            custom_genre = new String[jArray.length()];
            album = new String[jArray.length()];
            timestamp = new String[jArray.length()];
            song_id  = new String[jArray.length()];
            avatar = new String[jArray.length()];
            test_rating = new Float[jArray.length()];
            songurl = new String[jArray.length()];
            viewss = new String[jArray.length()];
            section = new String[jArray.length()];
            plays = new String[jArray.length()];
            downloads = new String[jArray.length()];
            ratingcount = new String[jArray.length()];
            commentcount = new String[jArray.length()];
            dlFlag = new int[jArray.length()];
            link1 = new String[jArray.length()];
            link2 = new String[jArray.length()];
            link3 = new String[jArray.length()];
            link4 = new String[jArray.length()];
            link5 = new String[jArray.length()];

            for(int i=0;i<jArray.length();i++){
                json_data = jArray.getJSONObject(i);
                song_id[i]=json_data.getString("id");
                song_name[i]=json_data.getString("songname");
                artist[i]=json_data.getString("artist");
                displayname[i]=json_data.getString("displayname");
                description[i]=json_data.getString("description");
                genre[i]=json_data.getString("genre");
                custom_genre[i]=json_data.getString("customgenre");
                album[i]=json_data.getString("album");
                timestamp[i]=json_data.getString("format");
                avatar[i]=json_data.getString("image_url");
                songurl[i]=json_data.getString("song_url");
                test_rating[i] = (float) json_data.getDouble("rating");
                viewss[i] = json_data.getString("views");
                section[i] = json_data.getString("section");
                plays[i] = json_data.getString("plays");
                downloads[i] = json_data.getString("downloads");
                ratingcount[i] = json_data.getString("rating_count");
                commentcount[i] = json_data.getString("comments");
                dlFlag[i] = json_data.getInt("downloadflag");
                link1[i] = json_data.getString("link1");
                link2[i] = json_data.getString("link2");
                link3[i] = json_data.getString("link3");
                link4[i] = json_data.getString("link4");
                link5[i] = json_data.getString("link5");
                user5  = new UserRecord(genre[i], displayname[i], timestamp[i], test_rating[i], songurl[i], viewss[i], song_id[i], avatar[i], description[i], section[i], plays[i], downloads[i], ratingcount[i], commentcount[i], dlFlag[i], link1[i], link2[i], link3[i], link4[i], link5[i]);

                publishProgress(user5);

            }
        }
        catch(JSONException e1){
            e1.printStackTrace();

        } catch (ParseException e1) {
            e1.printStackTrace();
        }           

        return null;
    }

    protected void onProgressUpdate(UserRecord... progress) {
        users.add(progress[0]);
    }

    protected void onPostExecute(JSONArray jArray) {                    

        filter = 0;
        loading = 0;
        adapterz.notifyDataSetChanged();
        if (dialog.isShowing()) {
            dialog.dismiss();
            }
        limit = limit + 20;
        listView.setOnScrollListener(new OnScrollListener(){
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int lastInScreen = firstVisibleItem + visibleItemCount;

                if (songcount.length != 0) {
                    if(lastInScreen == totalItemCount && loading == 0 && limit < songcount[0] && number != 55){
                        if (isNetworkAvailable() == false){
                            Toast toast = Toast.makeText(getApplicationContext(), "This app requires an internet connection", Toast.LENGTH_LONG);
                            toast.show();
                        } else {                                    
                            new LoadList().execute(link2);                      
                        }       

                    }
                }   
            }

            public void onScrollStateChanged(AbsListView view, int scrollState) {}
        });




    }

    protected void onPreExecute(){
        if (number == 2) {
            if (isNetworkAvailable() == false){
                Toast toast = Toast.makeText(getApplicationContext(), "This app requires an internet connection", Toast.LENGTH_LONG);
                toast.show();
            } else {                                    
                new SongCount().execute(genrecount);                        
            }       

        } else {
            if (isNetworkAvailable() == false){
                Toast toast = Toast.makeText(getApplicationContext(), "This app requires an internet connection", Toast.LENGTH_LONG);
                toast.show();
            } else {                                    
                new SongCount().execute(songcountphp);                      
            }   

        }
        loading = 1;
        if (filter == 1 || number == 55){
            adapterz.clear();
        }
        limitstring = limit.toString();
        nameValuePairs.add(new BasicNameValuePair("limit",limitstring));
        dialog = ProgressDialog.show(SongList.this, "", 
                "Loading. Please wait...", true);
    }
}

这就是它发生的那条线:

jArray = new JSONArray(result);

我怎样才能优雅地避免这种情况?谢谢!

2 个答案:

答案 0 :(得分:0)

要优雅,你需要进行空检查,或者在那里捕获NullPointerException,然后优雅地包含一些方法来静静地重试提取,或者通知用户错误。

答案 1 :(得分:0)

像凯文一样,我会做空检查。我还记得之前使用JSON + Android,如果我没记错的话,使用JSONArray总是给我带来麻烦。尝试使用:

jArray = new JSONObject(result);

JSONObject可以包含其他JSONObject或JSONArray的

有关详细信息,请参阅this链接。