40284

android: How to use asyncTask in Rest Web service?

Question:

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

Answer1:

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 : <a href="https://stackoverflow.com/a/13147992/693752" rel="nofollow">https://stackoverflow.com/a/13147992/693752</a> AsyncTask is not really the best tool to create network requests on Android.

Answer2:

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

Recommend

  • Filtering a CoreData FetchRequest
  • Filtering a CoreData FetchRequest
  • Java + jackson parsing error Unrecognized character escape
  • FATAL EXCEPTION java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/util/Args
  • Android and PHP Creating an API
  • Magento Shop by Brands [closed]
  • Converting json String to UTF-8
  • calling rest web service?
  • Android: How to make my retrieved (from mysql) JSON parsed data added to ListView refresh it self ev
  • retrofit 400 Bad Request
  • Posting data from android to PHP
  • Android json parse not working
  • Cannot use an @IdClass attribute for a @ManyToOne relationship
  • Android getAssets in Common class gives “The method getAsssets() is undefined for the type Context”
  • Append Textarea result from another class
  • Sending cookie value via httpget but not getting the desired response
  • Salesforce Different WSDL files and when to use
  • presentShareDialogWithParams posts to FB wall, but callback handler results say error
  • Time complexity of a program which involves multiple variables
  • Checking free space on FTP server
  • Spring security and special characters
  • Javascript convert timezone issue
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Upload files with Ajax and Jquery
  • Circular dependency while pushing http interceptor
  • AngularJs get employee from factory
  • Proper way to use connect-multiparty with express.js?
  • How to set the response of a form post action to a iframe source?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Change div Background jquery
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • apache spark aggregate function using min value
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • failed to connect to specific WiFi in android programmatically
  • How to push additional view controllers onto NavigationController but keep the TabBar?
  • How can I use threading to 'tick' a timer to be accessed by other threads?