android json Asynctask-发生Android运行时错误

时间:2014-04-30 08:20:10

标签: android json android-asynctask

 //檢查網路連線狀況
public void chkNetwork(){
    ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        Log.d("CHECK_POINT", "網路連線中 " );
        tv.setText("網路連線中");
        //呼叫AsyncTask
        new  DownloadWebpageTask().execute();

    } else {
        Log.d("CHECK_POINT", "網路斷線 ");
      tv.setText("網路斷線");
    }
}   
    private class DownloadWebpageTask extends AsyncTask<String[],Integer,String[]>
    {

        @Override
        protected String[] doInBackground(String[]... params) {
            try {
                return getWebData();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }        
        }



        @Override
        //背景工作處理完"後"需作的事
       protected void onPostExecute(String[] result) {
            super.onPostExecute(result);


           //進度BAR消失
           ProgressBar pb=(ProgressBar)findViewById(R.id.progressBar);
           pb.setVisibility(-1); 
           ArrayList<String> list=new ArrayList<String>();
           for(int i=0;i<result.length;i++){
               list.add(i,"recNo");
               list.add(i,"sort");
           }

           ArrayAdapter<String> listA=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_expandable_list_item_1,
                   list);
                   lv.setAdapter(listA);



        }

       //建立連線
        private DefaultHttpClient getHttpClient(){
            HttpParams httpparams = new BasicHttpParams();
            int timeoutConnection = 5000;
            HttpConnectionParams.setConnectionTimeout(httpparams,timeoutConnection);
            int timeoutSocket=3000;
            HttpConnectionParams.setSoTimeout(httpparams,timeoutSocket);
            DefaultHttpClient dfaultHC = new DefaultHttpClient(httpparams);
            return dfaultHC;
        }

        //取得網路資料
        public String[] getWebData() throws IOException{
            URL url=new URL("http://140.131.114.140/WebService/VB_test_browse.aspx");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);        
            conn.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String jsonString= reader.readLine();
            reader.close();

            try {

                Log.e("JSONdata",jsonString);
                return (getJson(jsonString));
            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            }
            /*String url ="http://140.131.114.140/WebService/VB_test_browse.aspx";
            HttpGet httpget = new HttpGet(url);
            try{
            HttpResponse httpresponse = getHttpClient().execute(httpget);
            String jSONdata=EntityUtils.toString(httpresponse.getEntity());
            Log.e("JSONdata",jSONdata);
            return (getJson(jSONdata));
            }catch(Exception err){
            return null;
            }*/

        }




 //將JSON字串解析
        public String[] getJson(String jsonString) throws JSONException {
        JSONArray jsonArr =new JSONArray(jsonString);
            //JSONArray jsonArray = jsonObject.getJSONArray(jsonString);
           String[] result = null;
           //String[] recNo = null;
          //  String[] sort = null;
            //String[] mMno =new String[jsonObject.length()];
          // String[] mName = null ;
            //String[] mTxt = null ;
            //ArrayList<String> mpic =new ArrayList<String>(jsonObject.length());
            //String[] itemArr = null ;
            for(int i=0;i<jsonArr.length();i++)
            {

                try{
                    JSONObject lib = jsonArr.getJSONObject(i);
                    Log.e("recNo",lib.getString("recNo"));
                    result[i] +=lib.getString("recNo");
                    result[i] +=lib.getString("sort");

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



            }
            return result;



        }

堆栈跟踪:

04-30 16:13:09.803: W/dalvikvm(9714): threadid=11: thread exiting with uncaught exception (group=0x4160fd88)
04-30 16:13:09.803: E/AndroidRuntime(9714): FATAL EXCEPTION: AsyncTask #1
04-30 16:13:09.803: E/AndroidRuntime(9714): Process: com.example.jsonconnet, PID: 9714
04-30 16:13:09.803: E/AndroidRuntime(9714): java.lang.RuntimeException: An error occured while executing doInBackground()
04-30 16:13:09.803: E/AndroidRuntime(9714):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
04-30 16:13:09.803: E/AndroidRuntime(9714):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
04-30 16:13:09.803: E/AndroidRuntime(9714):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
04-30 16:13:09.803: E/AndroidRuntime(9714):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
04-30 16:13:09.803: E/AndroidRuntime(9714):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-30 16:13:09.803: E/AndroidRuntime(9714):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-30 16:13:09.803: E/AndroidRuntime(9714):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-30 16:13:09.803: E/AndroidRuntime(9714):     at java.lang.Thread.run(Thread.java:841)
04-30 16:13:09.803: E/AndroidRuntime(9714): Caused by: java.lang.NullPointerException
04-30 16:13:09.803: E/AndroidRuntime(9714):     at com.example.jsonconnet.MainActivity$DownloadWebpageTask.getJson(MainActivity.java:179)
04-30 16:13:09.803: E/AndroidRuntime(9714):     at com.example.jsonconnet.MainActivity$DownloadWebpageTask.getWebData(MainActivity.java:140)
04-30 16:13:09.803: E/AndroidRuntime(9714):     at com.example.jsonconnet.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:81)
04-30 16:13:09.803: E/AndroidRuntime(9714):     at com.example.jsonconnet.MainActivity$DownloadWebpageTask.doInBackground(MainActivity.java:1)
04-30 16:13:09.803: E/AndroidRuntime(9714):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
04-30 16:13:09.803: E/AndroidRuntime(9714):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-30 16:13:09.803: E/AndroidRuntime(9714):     ... 4 more

1 个答案:

答案 0 :(得分:2)

getJson()中,您要为未初始化的result数组分配值。

考虑使用例如而是ArrayList<String>