Android的:如何在休息Web服务使用AsyncTask的? [英] android: How to use asyncTask in Rest Web service?

查看:332
本文介绍了Android的:如何在休息Web服务使用AsyncTask的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造的,我已经登录登出活动的Andr​​oid应用程序,Multilistview活动将数据从其他网络服务来了。这里的问题是,调用从登录活动WebService时,我得到错误的networkonmainthreadexception然后我搜索了有关异常护目镜,有人在堆栈溢出说使用的AsyncTask在code为分离线程,我在code实现的AsyncTask但不工作。我完全混淆了如何使用AsyncTask的,我想在下面的code添加的AsyncTask。我公司提供code,而不AsyncTask的,我做到了。任何人可以帮助我如何调用WebService时,正是使用AsyncTask的。

以下是编辑文本的通话功能。

获取数据

  UserFunctions userFun =新UserFunctions();        如果((username.trim()长度()方式> 0)及与放大器;(userpsw.trim()长度()大于0)){            JSONObject的JSON = userFun.loginUser(用户名,userpsw);
            。
                        。
                        。

下面是功能类

 公开的JSONObject loginUser(USEREMAIL字符串,字符串userPsw){        清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
        params.add(新BasicNameValuePair(标签,login_tag));
        params.add(新BasicNameValuePair(电子邮件,USEREMAIL));
        params.add(新BasicNameValuePair(密码,userPsw));
        JSONObject的JSON = jsonParser.getJsondataFromUrl(PARAMS);
       //Log.d(\"tag,json.toString());
        返回JSON;
    }

下面是实际WebService类

 公共无效getJsondataFromUrl(列表<&的NameValuePair GT; PARAMS){     {
        DefaultHttpClient的HttpClient =新DefaultHttpClient();
        HttpPost httpPost =新HttpPost(URL);
        httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));        HTT presponse HTT preSP = httpClient.execute(httpPost);
        HttpEntity httpEntity = HTT presp.getEntity();
        inStream中= httpEntity.getContent();
        //Log.d(tag,inStream.toString());
    }赶上(UnsupportedEncodingException五){
        e.printStackTrace();
    }赶上(ClientProtocolException E){
        e.printStackTrace();
    }赶上(IOException异常五){
        e.printStackTrace();
    }    尝试{
        的BufferedReader bufferReader =新的BufferedReader(新的InputStreamReader
                (插播广告,ISO-8859-1),8);
        StringBuilder的strBuilder =新的StringBuilder();
        串线= NULL;
        而((行= bufferReader.readLine())!= NULL){
            strBuilder.append(线+的n);
        }
        inStream.close();
        JSON = strBuilder.toString();
        //Log.d(\"JSON,JSON);
    }赶上(例外五){
        e.printStackTrace();
    }
    //尝试分析字符串到一个JSON对象
    尝试{
        jsonObj =新的JSONObject(JSON);
    }赶上(JSONException E){
        e.printStackTrace();
    }    返回jsonObj; * /
}

在此先感谢


解决方案

  @覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    的setContentView(R.layout.login);
    上下文=这一点;
    Log.v(TAG +的onCreate,在OnCreate称为);
    用户名=(的EditText)findViewById(R.id.editText_user);
    密码=(EditText上)findViewById(R.id.editText_psw);    btngo =(的ImageButton)findViewById(R.id.imageButton_go);
    btngo.setOnClickListener(本);}
@覆盖
公共无效的onClick(视图v){
     Log.v(TAG +的onClick,叫的onClick);
    如果(V == btngo)
    {
        用户= username.getText()的toString()修剪()。
        PSW = password.getText()的toString()修剪()。
                对话框= ProgressDialog.show(背景下,,请稍候...,真的!);              调用getResult结果=新调用getResult();
                result.execute();        }
    }}
私有类调用getResult扩展的AsyncTask<弦乐,太虚,字符串> {    @覆盖
    保护字符串doInBackground(字符串的URL ...){
        Log.v(TAG +.doInBackground,doInBackground方法调用);
        字符串response1 = NULL;           HttpClient的HttpClient的=新DefaultHttpClient();
           HttpPost httppost =新HttpPost(URL);
          // Log.d(回应,工作);
            尝试{                清单<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;();
                nameValuePairs.add(新BasicNameValuePair(web服务,1));
                nameValuePairs.add(新BasicNameValuePair(EMAIL_ID用户));
                nameValuePairs.add(新BasicNameValuePair(密码,PSW));                httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
                HTT presponse响应= httpclient.execute(httppost);
                InputStream为= response.getEntity()的getContent()。
                WebHelper webHelper =新WebHelper();
                response1 = webHelper.convertStreamToString(是);
                Log.v(TAG +。doInBackground,JSON的回应是:+ response1);        }赶上(ClientProtocolException E){
            // TODO自动生成catch块
            e.printStackTrace();
        }赶上(IOException异常五){
            // TODO自动生成catch块
            e.printStackTrace();
        }
        返回response1;
    }    @覆盖
    保护无效onPostExecute(字符串结果){        Log.v(TAG +.onPostExecute,onPostExecute方法调用);
        dialog.dismiss();
        Log.v(TAG +。onPostExecute,JSON的回应是:+结果);        / *意向意图=新意图(LoginActivity.this,ChoiceExamActivity.class);
         startActivity(意向);
         * /         如果(结果!= NULL){            尝试{
                // JSONTokener tokener =新JSONTokener(结果);
                JSONObject的resultObjct =新的JSONObject(结果);
                字符串USER_ID = resultObjct.getString(USER_ID);                如果(user_id.equalsIgnoreCase(0))
                {
                    ExamUtil.showAlert(LoginActivity.this,错误的用户名或密码);
                }
                其他
                {
                字符串名字= resultObjct.getString(将First_Name);
                Log.v(TAG +。onPostExecute,用户ID为:+ USER_ID);
                Log.v(TAG +。onPostExecute,名字是:+姓名);                 意向意图=新意图(LoginActivity.this,ChoiceExamActivity.class);
                 startActivity(意向);                }                }赶上(JSONException E){
                e.printStackTrace();
                }
               赶上(例外五){
                e.printStackTrace();
               }
             }         其他{                ExamUtil.showAlert(LoginActivity.this,我们在处理请求的一些问题,再试一次。);
            }
    }
}
}

I am creating apps in android in that I have login logout activity, Multilistview activity which data coming from rest web service. here problem is that when calling webservice from login activity I get error the networkonmainthreadexception then i searched on goggle about that exception, somebody said on stack overflow use AsyncTask in your code for seperation thread and I implemented asynctask in my code but not working. i am totally confusing how to use asynctask and I want to add asynctask in following code. I provide code without asynctask which i did. can anybody to help me how to exactly use asynctask when calling webservice.

following is the get data from edit text call function

UserFunctions userFun = new UserFunctions();

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

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

following is the function class

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;
    }

following is the actual webservice class

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;*/
}

Thanks in advance

解决方案

@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.");
            }




    }
}
}

这篇关于Android的:如何在休息Web服务使用AsyncTask的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆