0

I have a fragment in side a activity. I want to make a class that extend AsyncTask separately. How i can execute the AsyncTask from fragment and get value of Asyntask class in fragment. for example suppose it is my fragment class

public class FeePayFragment extends android.support.v4.app.Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootview = inflater.inflate(R.layout.fragment_fee_pay, container, false);}
}

and here is Asyntask

public class AsyFeeDues extends AsyncTask<Void,Void,Void> {
        JSONArray rootJsonArray;
        JSONObject rootJsonObject;
        private String compCode,session,admNo;
        boolean checkSeverResponse;
        public AsyFeeDues(String compCode, String session, String admNo) {
            this.compCode = compCode;
            this.session = session;
            this.admNo = admNo;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("Please Wait....");
            progressDialog.show();
        }
        @Override
        protected Void doInBackground(Void... params) {


            RestApi api = new RestApi();
            try {
                rootJsonObject = api.GetFeeDues(compCode, session, admNo);
                checkSeverResponse  = (rootJsonObject != null);
                if(checkSeverResponse) {
                    boolean isSuccess = rootJsonObject.optBoolean(TAG_SUCESSFULL);
                    rootJsonArray = rootJsonObject.optJSONArray(TAG_VALUE);

                    for (int i = 0; i < rootJsonArray.length(); i++) {

                        JSONObject jsonObject = rootJsonArray.optJSONObject(i);
                        int amount = jsonObject.optInt(TAG_AMOUNT);
                        if (amount > 0) {
                            int period = jsonObject.optInt(TAG_PERIOD);
                            if (period <= periodMonth) {
                                String feeCode = jsonObject.optString(TAG_FEECODE);
                                String feeHead = jsonObject.optString(TAG_FEEHEAD);
                                String periodName = jsonObject.optString(TAG_PERIODNAME);

                                boolean checkFeeKey = feeDuesDetails.containsKey(feeHead);
                                if (checkFeeKey) {
                                    totalBalanceAmount = totalBalanceAmount + amount;
                                    Map p = feeDuesDetails.get(feeHead);
                                    int previousAmount = (Integer) p.get(TAG_AMOUNT);
                                    int upDateAmount = previousAmount + amount;
                                    feeDuesDetails.get(feeHead).put(TAG_AMOUNT, upDateAmount);
                                } else {
                                    totalBalanceAmount = totalBalanceAmount + amount;
                                    map = new HashMap();
                                    map.put(TAG_AMOUNT, amount);
                                    feeDuesDetails.put(feeHead, map);
                                }
                            }
                        }


                    }

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


            return null;

        }
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialog.dismiss();
            if(checkSeverResponse) {
                if (feeDuesDetails.size() > 1) {
                    Set keys = feeDuesDetails.keySet();
                    for (Iterator i = keys.iterator(); i.hasNext(); ) {
                        String key = (String) i.next();
                        feeHead.add(key);
                        Map map = feeDuesDetails.get(key);
                        int feeHeadWiseAmount = (Integer) map.get(TAG_AMOUNT);
                        feeAmount.add(feeHeadWiseAmount);
                    }
                    feeDuesAdapter = new FeeDuesAdapter(getActivity(), feeHead, feeAmount);
                    feeDuesList.setAdapter(feeDuesAdapter);
                   totalAmountInRs.setText(String.valueOf(totalBalanceAmount));
                    paybleAmount.setText("Total Payable Amount");


                }
                else {
                    Toast.makeText(getActivity(), "Your fee paid up to this month", Toast.LENGTH_LONG).show();
                }
            }
            else {
                Toast.makeText(getActivity(), "Server not response", Toast.LENGTH_LONG).show();
            }
        }

I want all value in my fragment that is retrieve in doInBackground method variable like feecode,feehead,period etc

  • please add interface and call it form u r onPostExecute method and get a call back in u r fragmet – Ganesh Gudghe Dec 03 '15 at 13:56
  • This answer may help you [enter link description here](http://stackoverflow.com/questions/13815807/return-value-from-asynctask-class-onpostexecute-method) – ketankk Dec 03 '15 at 14:28
  • http://stackoverflow.com/questions/13815807/return-value-from-asynctask-class-onpostexecute-method[This type of issue has been resloved on stackoverflow][1] – ketankk Dec 03 '15 at 14:29

2 Answers2

0

How do you mean? To get objects from your Asynctask you must return a value in do inbackground(). In order to do that you have to parse your JSON in objects(models) so you can return a fee-object. Once you have this, you will have to update your ui when the data is loaded.

SamuelD
  • 333
  • 2
  • 10
0

AsyncTask has three parameters defined for it:

The three types used by an asynchronous task are the following:

  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.

Go through the google docs for clarification: http://developer.android.com/reference/android/os/AsyncTask.html

You can achieve that by doing the following:

An interface to handle such things:

public interface MyListener{
     public void onTaskComplete(int status, String data);
}

Then your asynctask

public class MyAsyncTask extends AsyncTask<Void, Void, String>{

    MyListener mMyListener;
    public MyAsyncTask(MyListener myListener){
         mMyListener = myListener;
    }
    ...
    public String doInBackground(Void... params){
         String valueToReturn;
         //Your code here to get the required data to set the "valueToRetun"
         return valueToReturn;
    }
    ...
    public void onPostExecute(String data){ <- you get that data here
         //Your code here
         mMyListener.onTaskComplete(1, data); <- 1  being the success status
    }
}

Let your activity implement the listener:

public class MyActivity implements MyLisntener{
     ...Your code here
     public void startTask(){
          MyAsyncTask mt = new MyAsyncTask(this);
          mt.execute();
     }

     @Override
     public void onTaskComplete(String data){
          //Process your data here
     }

     ...Your code here
}

I'm assuming you need to return String. Replace it with your modal object in case you are expecting the asynctask to return something else.

Hope it helps :)

avin
  • 459
  • 5
  • 14