如何在此代码中实现AsyncTask。

时间:2014-01-10 12:03:14

标签: android json parsing android-asynctask

这是我的代码。我试图扩展AsyncTask但它不起作用。这是我的代码。 运行My App时显示NetworkOnMainThread异常。我是android的新手,我需要开发一个登录系统。

    public class JSONParser extends AsyncTask<String,Void,JSONObject>{
    static InputStream  mInputStream=null;
    static JSONObject mJsonObject=null;
    static String json="";
    String url="";
    List<NameValuePair> params=null;

    public JSONParser() {
    }

    public JSONObject getJsonFromURL(String url,List<NameValuePair> params){
        url=this.url;
        params=this.params;
    return doInBackground();
    }

    protected JSONObject doInBackground(String... params) {
        try{
            DefaultHttpClient httpClient=new DefaultHttpClient();
            HttpPost httpPost=new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse=httpClient.execute(httpPost);
            HttpEntity httpEntity=httpResponse.getEntity();
            mInputStream=httpEntity.getContent();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try{
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(mInputStream,"iso-8859-1"),8);
            StringBuilder sb=new StringBuilder();
            String line= null;
            while((line=bufferedReader.readLine())!=null){
                sb.append(line).append("\n");
            }
            bufferedReader.close();
            json=sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            mJsonObject = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        return mJsonObject;
       }
}

我不知道是不是正确的方式。 请帮我。 httpPost.setEntity(new UrlEncodedFormEntity(params)); 此行显示错误,不知道如何删除它。不适用于String []

1 个答案:

答案 0 :(得分:1)

创建回拨接口

public interface CallBack {
    void run(Object result);
}

RequestClient类

public class RequestClient extends AsyncTask<String, Void, String> {
    Context context;
    CallBack callBack;

    public RequestClient(CallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //LoginPage.progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        String responseString = "";
        HttpClient client = null;
        try {
            client = new DefaultHttpClient();
            HttpGet get = new HttpGet(LoginPage.url);
            client.getParams().setParameter("http.socket.timeout", 6000);
            client.getParams().setParameter("http.connection.timeout", 6000);
            HttpResponse responseGet = client.execute(get);
            HttpEntity resEntityGet = responseGet.getEntity();
            if (resEntityGet != null) {
                responseString = EntityUtils.toString(resEntityGet);
                Log.i("GET RESPONSE", responseString.trim());
            }
        } catch (Exception e) {
            Log.d("ANDRO_ASYNC_ERROR", "Error is " + e.toString());
        }
        Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
        client.getConnectionManager().shutdown();
        return responseString.trim();
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        callBack.run(result);
        //LoginPage.progressDialog.dismiss();
    }
}

在登录活动中

RequestClient reqClient = new RequestClient(new CallBack() {

            @Override
            public void run(Object result) {
                try {
                    AppResponse = (String) result;

                    String status =ValidateLoginStatus.checkLoginStatus(AppResponse);
                    Log.d("TAG Status recived", status);

                    if (status.equals("300")) {
                        saveInformation(userId, pass);
                        startingActivity();
                    } else {
                        error.setText("Incorrect UserName or Password");
                    }
                } catch (Exception e) {
                    Log.e("TAG Exception Occured",
                            "Exception is " + e.getMessage());
                }
            }
        });
        reqClient.execute(url);