Get the result from async task

若如初见. 提交于 2019-12-02 12:22:42

1-I don't know when to process the result?

The result will be processed in onPostExecute, which in turn will call your interface method in whatever class is implementing this interface. So the actual UI stuff will all take place in your Activity or Fragment or whatever is implementing the interface callback. You can pass any data you want to it.

2-why to use interface?

An interface is a great way to decouple the logic from your AsyncTask and whatever class (I assume an Activity or Fragment) that is implementing it. Also this means that any class that implements this interface can process results from this AsyncTask, it become easily re-usable.

3-What's the differences of using an interface with simply putting the result in a public field in Async task from onPostExecute?

You still won't get a callback - how will your Activity or Fragment know when this field is populated and ready to be interrogated?

For your concern with basics ..

Step (1) Initiate Async Task

new BussinessOwnerHttpAsyncTask().execute();

Step (2) Create your AsyncTask class like this

    class BussinessOwnerHttpAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
// Here U perform all your basics task like start showing progress bar as mentioned below.  //@Android Hacker 
// On OnPostExecute method U stop your progress dialog after all data has been fetched 
// @Android Hacker 
            pDialog = new ProgressDialog(getParent());
            pDialog.setMessage("Please wait ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {


// Here U fetch all data from server @Android Hacker 

            //  Maintaining Shared preferences class for further...

            SharedPreferences sp = getSharedPreferences("search_data", 0);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("service_name", service_name);
            editor.putString("city_name", city_name);
            editor.putString("loc", city_name + ", " + country_name);
            editor.putString("country_name", country_name);
            editor.putString("pMonth", (checkDigit(pMonth + 1)));
            editor.putString("day", day);
            editor.putString("year", year);
            editor.putString("d", year + "-" + checkDigit(pMonth + 1) + "-" + day);
            editor.commit();

            HttpClient httpclient = new DefaultHttpClient();
            String loc = "";
            String sdate = "";

            try{

                if(pDisplayDate.getText().toString().equalsIgnoreCase("")){
                    sdate = year + "-" + checkDigit(pMonth + 1) + "-" + day;
                }else{
                    sdate = date;
                }
            }catch(Exception e){
                e.printStackTrace();
            }

            if(etlocation.getText().toString().length() == 0){
                city_name = "";
                country_name = "Kuwait";
                loc = "" + ", " + "Kuwait";
            }else{
                loc = city_name + ", " + country_name;
            }


            String myUrl = service_name + "~" + city_name + "~"
                    + country_name + "~" + date
                    + "~" + service_recog_id;

            if(city_name.equalsIgnoreCase("")){
                locations = "Kuwait"; 
            }else{
                locations = city_name + ", " + country_name;
            }

            SharedPreferences m = getSharedPreferences("modify", 0);
            SharedPreferences.Editor eee = m.edit();
            eee.putString("service", service_name);
            eee.putInt("service_recog_id", service_recog_id);
            eee.putString("location", loc);
            eee.putString("date", sdate);
            eee.putString("locations", locations);
            eee.commit();


            String encodedURL = "";
            try {
                encodedURL = URLEncoder.encode(myUrl, "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                URL url = new URL(encodedURL);
                Log.d("asca", ""+url);
            } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            Log.i("url", city_name + "~" + country_name);
            Log.d("location", request_url+encodedURL);
            HttpGet httpget = new HttpGet(request_url+encodedURL);

            try {
                httpresponse = httpclient.execute(httpget);
                System.out.println("httpresponse" + httpresponse);
                Log.i("response", "Response" + httpresponse);
                InputStream is = httpresponse.getEntity().getContent();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();

                String recievingDataFromServer = null;
                while ((recievingDataFromServer = br.readLine()) != null) {
                    Log.i("CHECK WHILE", "CHECK WHILE");
                    sb.append(recievingDataFromServer);
                }

                myJsonString = sb.toString();
                Log.d("manish", myJsonString);
                serverSearchData = sb.toString();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return sb.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            pDialog.dismiss();

 // @Android Hacker .. Here U perform all your task for UI . Here U get data and set that //data to UI 


        }

    }

Hope it clears all your doubts..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!