Nilesh
Nilesh

Reputation: 93

android: How to use asyncTask in Rest Web service?

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

Upvotes: 1

Views: 7543

Answers (2)

Sunil Kumar
Sunil Kumar

Reputation: 7092

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




    }
}
}

Upvotes: 2

Snicolas
Snicolas

Reputation: 38168

Create a class that inherit from AsyncTask. In doInBackground call your network code and return a POJO. In postExecute, update your views using this POJO. Follow the signature of AsyncTask's method to understand how to type your sublcass with generics.

You should also consider this thread : https://stackoverflow.com/a/13147992/693752 AsyncTask is not really the best tool to create network requests on Android.

Upvotes: 2

Related Questions