使用Async Task方法时Android Null指针异常

时间:2015-10-06 05:47:16

标签: android json asynchronous

在android中执行Async Task并获取Json响应并将响应转换为JSONArray时,我得到NUll指针异常。 我正在尝试两天请帮助我。 这是获取Json String的代码。 错误发生在task.get()。

DownloadTask task=new DownloadTask();
        task.execute(new String[]{"URL"});
        try {
            jsonArr=new JSONArray(task.get());
                Toast.makeText(getApplicationContext(), jsonArr.toString(), Toast.LENGTH_LONG).show();
                for (int i = 0; i < jsonArr.length(); i++) {
                    obj = jsonArr.getJSONObject(i);
                    name = obj.getString("name");
                    phno = obj.getString("phone");
                    dcount = obj.getString("count");
                }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

这是异步任务代码。

class DownloadTask extends AsyncTask<String,Void,String>{

        private ProgressDialog mProgressDialog=new ProgressDialog(MainActivity.this);

        @Override
        protected void onPreExecute(){
            mProgressDialog.setMessage("Processing");
            mProgressDialog.show();
        }

        @Override
        protected String doInBackground(String... targetURL) {
            URL url;
            HttpURLConnection connection = null;
            try {

                url = new URL(targetURL[0]);
                connection = (HttpURLConnection)url.openConnection();

                connection.setRequestMethod("GET");
                connection.setRequestProperty("Content-Type",
                        "application/json");

                connection.setUseCaches (false);
                connection.setDoInput(true);
                connection.setDoOutput(true);

             /*   //Send request
                DataOutputStream wr = new DataOutputStream (
                        connection.getOutputStream ());
                wr.writeBytes("BID1");
                wr.flush();
                wr.close();*/

                //Get Response
                InputStream is = connection.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                String line;
                StringBuffer response = new StringBuffer();
                while((line = rd.readLine()) != null) {
                    response.append(line);
                    response.append('\r');
                }
                rd.close();
                return response.toString();

            } catch (Exception e) {
                e.printStackTrace();
                return null;

            } finally {

                if(connection != null) {
                    connection.disconnect();
                }
            }
        }
        @Override
        protected void onPostExecute(String result) {

            Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT);
            mProgressDialog.dismiss();

        }
    }

1 个答案:

答案 0 :(得分:0)

您忘记调用onPostExecute

的超级方法

应该是这样的

@Override
protected void onPostExecute(String result) {

    Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT);
    mProgressDialog.dismiss();
    super.onPostExecute(result);
}

其他解决方案

您可以使用接口进行回调

ICallback.java

public interface ICallback {
    void onResult(String result);
}

DownloadTask

class DownloadTask extends AsyncTask<String, Void, String> {
    private ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);
    private ICallback callback;

    public DownloadTask(ICallback callback) {
        this.callback = callback;
    }

    @Override
    protected void onPreExecute() {
        //Your Codes Here
    }

    @Override
    protected String doInBackground(String... targetURL) {
        //Your Codes Here
    }

    @Override
    protected void onPostExecute(String result) {
        //Your Codes Here
        callback.onResult(result)
    }
}

如何使用

DownloadTask task = new DownloadTask(new ICallback() {
    @Override
    public void onResult(String result) {
        try {
            jsonArr=new JSONArray(result);
            Toast.makeText(getApplicationContext(), jsonArr.toString(), Toast.LENGTH_LONG).show();
            for (int i = 0; i < jsonArr.length(); i++) {
                obj = jsonArr.getJSONObject(i);
                name = obj.getString("name");
                phno = obj.getString("phone");
                dcount = obj.getString("count");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}); 

task.execute(new String[]{"URL"});