1

我在 android 中创建应用程序,因为我有登录注销活动、Multilistview 活动,这些活动的数据来自其他 Web 服务。这里的问题是,当从登录活动调用 web 服务时,我收到 networkonmainthreadexception 错误,然后我在 goggle 上搜索该异常,有人说堆栈溢出在你的代码中使用 AsyncTask 用于分离线程,我在我的代码中实现了 asynctask 但没有工作。我完全混淆了如何使用 asynctask,我想在下面的代码中添加 asynctask。我提供的代码没有我所做的 asynctask。任何人都可以帮助我在调用 webservice 时如何准确地使用 asynctask。

以下是从编辑文本调用函数中获取数据

UserFunctions userFun = new UserFunctions();

        if ((username.trim().length() > 0)&&(userpsw.trim().length() > 0)) {

            JSONObject json = userFun.loginUser(username, userpsw);
            .
                        .
                        .

以下是函数类

public JSONObject loginUser(String userEmail, String userPsw) {

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", login_tag));
        params.add(new BasicNameValuePair("email", userEmail));
        params.add(new BasicNameValuePair("password", userPsw));
        JSONObject json = jsonParser.getJsondataFromUrl(params);
       //Log.d("tag", json.toString());
        return json;
    }

以下是实际的网络服务类

public void getJsondataFromUrl(List<NameValuePair> params) {

     {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResp = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResp.getEntity();
        inStream = httpEntity.getContent();
        //Log.d(tag, inStream.toString());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader bufferReader = new BufferedReader(new InputStreamReader
                (inStream, "iso-8859-1"), 8);
        StringBuilder  strBuilder = new StringBuilder();
        String line = null;
        while ((line = bufferReader.readLine()) != null) {
            strBuilder.append(line + "n");
        }
        inStream.close();
        json = strBuilder.toString();
        //Log.d("JSON", json);
    } catch (Exception e) {
        e.printStackTrace();
    } 
    // try parse the string to a JSON object
    try {
        jsonObj = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonObj;*/
}

提前致谢

4

2 回答 2

2

创建一个继承自 AsyncTask 的类。在doInBackground调用您的网络代码并返回一个 POJO。在postExecute中,使用此 POJO 更新您的视图。按照 AsyncTask 方法的签名来了解如何使用泛型键入子类。

您还应该考虑这个线程:https: //stackoverflow.com/a/13147992/693752 AsyncTask 并不是在 Android 上创建网络请求的最佳工具。

于 2013-04-16T06:12:05.553 回答
2
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);  
    setContentView(R.layout.login);
    context=this;


    Log.v(TAG+"onCreate", "OnCreate Called");
    username = (EditText)findViewById(R.id.editText_user);
    password = (EditText)findViewById(R.id.editText_psw);

    btngo = (ImageButton)findViewById(R.id.imageButton_go);
    btngo.setOnClickListener(this);



}
@Override
public void onClick(View v) {
     Log.v(TAG+"onClick", "onClick Called");
    if(v== btngo)
    {
        user=username.getText().toString().trim();
        psw=password.getText().toString().trim();


                dialog = ProgressDialog.show(context, "", "Please! Wait...",true);

              GetResult result = new GetResult();
                result.execute();

        }
    }

}
private class GetResult extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {
        Log.v(TAG + ".doInBackground", "doInBackground method call");
        String response1 = null;

           HttpClient httpclient = new DefaultHttpClient();
           HttpPost  httppost = new HttpPost("url");
          //  Log.d("response", "WORKING");
            try {

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("webservice", "1"));
                nameValuePairs.add(new BasicNameValuePair("Email_ID", user));
                nameValuePairs.add(new BasicNameValuePair("Password",psw));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                InputStream is = response.getEntity().getContent();
                WebHelper webHelper = new WebHelper();
                response1 = webHelper.convertStreamToString(is);
                Log.v(TAG+".doInBackground", "json response is:" + response1);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return response1;


    }

    @Override
    protected void onPostExecute(String result) {

        Log.v(TAG + ".onPostExecute", "onPostExecute method call");
        dialog.dismiss();
        Log.v(TAG+".onPostExecute", "json response is:" + result);

        /* Intent intent= new Intent(LoginActivity.this, ChoiceExamActivity.class);
         startActivity(intent);
         */

         if(result!=null){

            try {
                //JSONTokener tokener = new JSONTokener(result);
                JSONObject resultObjct = new JSONObject(result);
                String user_id=resultObjct.getString("User_ID");

                if(user_id.equalsIgnoreCase("0"))
                {
                    ExamUtil.showAlert(LoginActivity.this,"Incorrect User name or password");
                }
                else
                {
                String firstname = resultObjct.getString("First_Name");
                Log.v(TAG+".onPostExecute", "user id is:" + user_id);
                Log.v(TAG+".onPostExecute", "firstname is:" + firstname);



                 Intent intent= new Intent(LoginActivity.this, ChoiceExamActivity.class);
                 startActivity(intent);

                }

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

         else{  

                ExamUtil.showAlert(LoginActivity.this,"We have some problem in processing request, try again.");
            }




    }
}
}
于 2013-04-16T06:20:11.663 回答