安卓:回调的AsyncTask到碎片(不活动)回调、碎片、AsyncTask

2023-09-03 21:36:16 作者:野的像风/傲的像光

我想实现的AsyncTask和片段的回调,但无法找到正确的信息如何做到这一点。问题是,所有的回调实现的活动和AsyncTask的之间,但我需要片段的AsyncTask之间。可能有人给我小的工作示例如何实现它没有活性。 我的动作结构:分片通话DialogFragment - >选择一些和服务器发送请求的异步任务 - >异步任务过程中的一切,更新视图和一些变量。我的主要问题是,我称之为prepareData()只有一次的onCreate,当我走其他片段与回报之间回来我看到旧数据。这就是说没有足够的更新的​​AsyncTask的onPOST等只读视图。这将是件好事,回调将更新整个变量。

 公共类TermsAndConditionsFragment扩展SherlockFragment实现OnClickListener,OnTouchListener,OnItemClickListener,onTaskListener {
 @覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);

    FM = getSherlockActivity()getSupportFragmentManager()。


    prepareData();
}

公共无效prepareData(){
     termsAndConditionsM =新TermsAndConditionsManager(getSherlockActivity());
    termsAndConditions = termsAndConditionsM.getTermsAndConditions();

    如果(termsAndConditions!= NULL){
                 INT totalPayments = Integer.valueOf(termsAndConditions.get(ServerAPI.NO_OF_PAYMENTS));
        如果(totalPayments大于0){
            paymentsData = termsAndConditionsM.getpayments();

            如果(paymentsData!= NULL){

                付款=新的ArrayList<支付>();

                的for(int i = 1; I< = totalPayments;我++){
                    paymentValues​​ =新的支付();
                    paymentValues​​.setPaymentID(Integer.valueOf(paymentsData.get(ServerAPI.PAYMENT_NO +_+ I)));
                    paymentValues​​.setPaymentDate(paymentsData.get(ServerAPI.PAYMENT_DATE +_+ i)段);
                    paymentValues​​.setPaymentTotalAmount(paymentsData.get(ServerAPI.PAYMENT_TOTAL +_+ i)段);
                    payments.add(paymentValues​​);
                }
            }
        }
    }
}

@覆盖
公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,捆绑savedInstanceState){

    rootView =的init(充气,容器);

    如果(付款!= NULL || termsAndConditions!= NULL)
        updateTermsAndConditionsView();

    返回rootView;
}

私有视图的init(LayoutInflater充气,容器的ViewGroup){
    rootView = inflater.inflate(R.layout.fragment_terms_and_conditions,集装箱,假);

    ...
    返回rootView;
}

公共无效updateTermsAndConditionsView(){
    etHowMuch.setText(£+ termsAndConditions.get(ServerAPI.AMOUNT_OF_CREDIT));
    etForHowLong.setText(Helpers.ConvertDays2Date(Integer.valueOf(termsAndConditions.get(ServerAPI.TERM_OF_AGREEMENT_IN_DAYS))));

    PaymentAdapter适配器=新PaymentAdapter(getSherlockActivity(),R.layout.custom_loan_item,支付);
    lvPayments.setAdapter(适配器);

    tvNoOfPayments.setText(termsAndConditions.get(ServerAPI.NO_OF_PAYMENTS));
    tvFirstPayment.setText(termsAndConditions.get(ServerAPI.FIRST_PAYMENT_DATE));
    tvTotalRepayable.setText(£+ termsAndConditions.get(ServerAPI.TOTAL_REPAYABLE));
}

@覆盖
公共无效的onClick(视图v){
    英尺= fm.beginTransaction();

    howMuch = etHowMuch.getText()的toString()。
    。forHowLong = etForHowLong.getText()的toString();

    开关(v.getId()){
        案例R.id.etHowMuch:
            F =新NumberPaymentsPickerFragment();
            的args =新包();
            args.putInt(Const.HOW_MUCH,Integer.valueOf(howMuch.replace(£,)));
            args.putDouble(ServerAPI.PAYMENT_STEP,Const.PAYMENT_STEP);
            args.putString(Const.STATE,ServerAPI.TERMS_AND_CONDITIONS);
            f.setArguments(参数);
            f.setTargetFragment(这一点,DIALOG_FRAGMENT);
            f.show(getActivity()getSupportFragmentManager(),Const.HOW_MUCH。);
            打破;
        案例R.id.etForHowLong:
            F =新NumberPaymentsPickerFragment();
            的args =新包();
            args.putInt(Const.FOR_HOW_LONG,Integer.valueOf(Helpers.ConvertDate2Days(forHowLong)));
            args.putDouble(ServerAPI.PAYMENT_STEP,Const.PAYMENT_STEP);
            args.putString(Const.STATE,ServerAPI.TERMS_AND_CONDITIONS);
            f.setArguments(参数);
            f.setTargetFragment(这一点,DIALOG_FRAGMENT);
            f.show(getActivity()getSupportFragmentManager(),Const.FOR_HOW_LONG。);
            打破;
        案例R.id.tvPersonalDetails:
            sfm.saveCurFragment(ServerAPI.PERSONAL_DETAILS,0);
            ft.replace(android.R.id.content,新PersonalDetailsFragment(),ServerAPI.PERSONAL_DETAILS).addToBackStack(空).commit();
            打破;
        案例R.id.tvAgreementDetails:
            sfm.saveCurFragment(ServerAPI.AGREEMENT_DETAILS,0);
            ft.replace(android.R.id.content,新AgreementDetailsFragment(),ServerAPI.AGREEMENT_DETAILS).addToBackStack(空).commit();
            打破;
        案例R.id.bApply:

            打破;
    }

@覆盖
公共无效onUpdateData(){
    Log.d(TAG,更新数据);

}

}
 

DialogFragment:

  @覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);

    捆绑的args = getArguments();

    ...
}

公共对话onCreateDialog(包savedInstanceState){

    ...

        CreateDialog函数返回(V,R.string.for_how_long,etHowMuch,etForHowLong,etPromotion code);
    }
    返回null;
}
私人CreateDialog函数对话框(视图中查看,INT titleResID,最终的EditText howMuchField,最终的EditText forHowLongField,最终的EditText促销codeField){
    AlertDialog.Builder建设者=新AlertDialog.Builder(getActivity());
    builder.setTitle(titleResID);
    builder.setView(视图);
    builder.setPositiveButton(R.string.set,新DialogInterface.OnClickListener(){
        @覆盖
        公共无效的onClick(DialogInterface对话框,INT ID){

            doShowProgress();

        }

        私人无效doShowProgress(){


            ExecuteServerTaskBackground任务=新
                    ExecuteServerTaskBackground(getActivity());
                task.action = ServerAPI.GET_TERMS_AND_CONDITIONS;
                onTaskListener监听器=新onTaskListener(){

                @覆盖
                公共无效onUpdateData(){
                    Log.d(TAG,Updaaate);

                }
            };
            task.setListener(听众);
            task.args = ARGS;
            task.execute();
        }

    })。setNegativeButton(R.string.cancel,新DialogInterface.OnClickListener(){
        @覆盖
        公共无效的onClick(DialogInterface对话框,INT ID){
            dialog.cancel();
        }
    });
    返回builder.create();
}
 

AsyncTask的:

  onTaskListener mListener;

公共接口onTaskListener {
    无效onUpdateData();
}

公共无效使用setListener(onTaskListener监听器){
  mListener =侦听器;
}
公共ExecuteServerTaskBackground(活动活动){
    this.mActivity =活动;
    this.mContext = activity.getApplicationContext();
}

@覆盖
在preExecute保护无效(){
    PB =(进度)mActivity.findViewById(R.id.progressBar1);
    pb.setVisibility(View.VISIBLE);
}

@覆盖
保护无效doInBackground(虚空...... PARAMS){
    ServerAPI服务器=新ServerAPI(mContext);
    如果(!args.isEmpty())
        server.serverRequest(操作,参数);
    其他
        server.serverRequest(动作,NULL);
    返回null;
}

@覆盖
保护无效onPostExecute(无效的结果){
 mListener.onUpdateData();

//还有就是我刚刚更新的看法,但如何更新整个变量throughtout回调?
// tvNoOfPayments =(TextView中)mActivity.findViewById(R.id.tvNoOfPaymentsValue);
// tvFirstPayment =(TextView中)mActivity.findViewById(R.id.tvFirstPaymentValue);
// tvTotalRepayable =(TextView中)mActivity.findViewById(R.id.tvTotalRepayableValue);
//
// lvPayments =(ListView控件)mActivity.findViewById(R.id.lvData);
//
// termsConditionsM =新TermsAndConditionsManager(mContext);
//
// termsAndConditions = termsConditionsM.getTermsAndConditions();
//
// INT totalPayments = Integer.valueOf(termsAndConditions.get(ServerAPI.NO_OF_PAYMENTS));
//
//如果(totalPayments大于0){
//如果(termsAndConditions!= NULL){
// tvNoOfPayments.setText(termsAndConditions.get(ServerAPI.NO_OF_PAYMENTS));
// tvFirstPayment.setText(termsAndConditions.get(ServerAPI.FIRST_PAYMENT_DATE));
// tvTotalRepayable.setText(£+ termsAndConditions.get(ServerAPI.TOTAL_REPAYABLE));
//}
//
// paymentsData = termsConditionsM.getpayments();
//
//如果(paymentsData!= NULL){
// Log.d(TAG,paymentsData.toString());
//
//付款=新的ArrayList<支付>();
//
//的for(int i = 1; I< = totalPayments;我++){
// paymentValues​​ =新的付款方式();
// paymentValues​​.setPaymentID(Integer.valueOf(paymentsData.get(ServerAPI.PAYMENT_NO +_+ I)));
// paymentValues​​.setPaymentDate(paymentsData.get(ServerAPI.PAYMENT_DATE +_+ i)段);
// paymentValues​​.setPaymentTotalAmount(paymentsData.get(ServerAPI.PAYMENT_TOTAL +_+ i)段);
// payments.add(paymentValues​​);
//}
//
// PaymentAdapter适配器=新PaymentAdapter(mContext,R.layout.custom_loan_item,支付);
// lvPayments.setAdapter(适配器);
//}
    //

   }

    pb.setVisibility(View.GONE);
    super.onPostExecute(结果);
}
 
AsyncTask研究 以Android 10.0为准

解决方案

如果不花你的code考虑我会后最重要的做一个​​功能的回调。

TestFragment:

 公共类TestFragment扩展片段{

    / *跳过最code,我只会告诉你最重要的。 * /
    私人无效methodThatStartsTheAsyncTask(){
        TestAsyncTask testAsyncTask =新TestAsyncTask(新FragmentCallback(){

            @覆盖
            公共无效onTaskDone(){
                methodThatDoesSomethingWhenTaskIsDone();
            }
        });

        testAsyncTask.execute();
    }

    私人无效methodThatDoesSomethingWhenTaskIsDone(){
        /* 魔法! * /
    }

    公共接口FragmentCallback {
        公共无效onTaskDone();
    }
}
 

TestAsyncTask:

 公共类TestAsyncTask扩展的AsyncTask<虚空,虚空,虚空> {
    私人FragmentCallback mFragmentCallback;

    公共TestAsyncTask(FragmentCallback fragmentCallback){
        mFragmentCallback = fragmentCallback;
    }

    @覆盖
    保护无效doInBackground(虚空...... PARAMS){
        / *做你的事。 * /
        返回null;
    }

    @覆盖
    保护无效onPostExecute(无效的结果){
        mFragmentCallback.onTaskDone();
    }
}
 

I am trying to implement callback between AsyncTask and Fragment but cannot find correct info how to do it. The issue is that all callback implementations are between activity and asynctask but I need between fragment and asynctask. Could someone give me small working example how to implement it without activity. My action structure: Fragment call DialogFragment -> choose something and send server request to async task -> async task process everything and update view and some variables. My main problem is that I call prepareData() only once in onCreate and when I walk between other fragment and returns come back I see old data. That is to say there is not enough to update only view in onPost of asynctask. It will be good to have callback which will update the whole variables.

public class TermsAndConditionsFragment extends SherlockFragment implements OnClickListener, OnTouchListener, OnItemClickListener, onTaskListener {
 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    fm = getSherlockActivity().getSupportFragmentManager();


    prepareData();
}

public void prepareData() {
     termsAndConditionsM = new TermsAndConditionsManager(getSherlockActivity());
    termsAndConditions = termsAndConditionsM.getTermsAndConditions();

    if (termsAndConditions != null) {
                 int totalPayments = Integer.valueOf(termsAndConditions.get(ServerAPI.NO_OF_PAYMENTS));
        if (totalPayments > 0) {
            paymentsData = termsAndConditionsM.getpayments();

            if (paymentsData != null) {

                payments = new ArrayList<Payment>();

                for (int i = 1; i <= totalPayments; i++) {
                    paymentValues = new Payment();
                    paymentValues.setPaymentID(Integer.valueOf(paymentsData.get(ServerAPI.PAYMENT_NO + "_" + i)));
                    paymentValues.setPaymentDate(paymentsData.get(ServerAPI.PAYMENT_DATE + "_" + i));
                    paymentValues.setPaymentTotalAmount(paymentsData.get(ServerAPI.PAYMENT_TOTAL + "_" + i));
                    payments.add(paymentValues);
                }
            }
        }
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    rootView = init(inflater, container);

    if (payments != null || termsAndConditions != null)
        updateTermsAndConditionsView();

    return rootView;
}

private View init(LayoutInflater inflater, ViewGroup container) {
    rootView = inflater.inflate(R.layout.fragment_terms_and_conditions, container, false);

    ...
    return rootView;
}

public void updateTermsAndConditionsView() {
    etHowMuch.setText("£" + termsAndConditions.get(ServerAPI.AMOUNT_OF_CREDIT));
    etForHowLong.setText(Helpers.ConvertDays2Date(Integer.valueOf(termsAndConditions.get(ServerAPI.TERM_OF_AGREEMENT_IN_DAYS))));

    PaymentAdapter adapter = new PaymentAdapter(getSherlockActivity(), R.layout.custom_loan_item, payments);
    lvPayments.setAdapter(adapter);

    tvNoOfPayments.setText(termsAndConditions.get(ServerAPI.NO_OF_PAYMENTS));
    tvFirstPayment.setText(termsAndConditions.get(ServerAPI.FIRST_PAYMENT_DATE));
    tvTotalRepayable.setText("£" + termsAndConditions.get(ServerAPI.TOTAL_REPAYABLE));
}

@Override
public void onClick(View v) {
    ft = fm.beginTransaction();

    howMuch = etHowMuch.getText().toString();
    forHowLong = etForHowLong.getText().toString();

    switch (v.getId()) {
        case R.id.etHowMuch:
            f = new NumberPaymentsPickerFragment();
            args = new Bundle();
            args.putInt(Const.HOW_MUCH, Integer.valueOf(howMuch.replace("£", "")));
            args.putDouble(ServerAPI.PAYMENT_STEP, Const.PAYMENT_STEP);
            args.putString(Const.STATE, ServerAPI.TERMS_AND_CONDITIONS);
            f.setArguments(args);
            f.setTargetFragment(this, DIALOG_FRAGMENT);
            f.show(getActivity().getSupportFragmentManager(), Const.HOW_MUCH);
            break;
        case R.id.etForHowLong:
            f = new NumberPaymentsPickerFragment();
            args = new Bundle();
            args.putInt(Const.FOR_HOW_LONG, Integer.valueOf(Helpers.ConvertDate2Days(forHowLong)));
            args.putDouble(ServerAPI.PAYMENT_STEP, Const.PAYMENT_STEP);
            args.putString(Const.STATE, ServerAPI.TERMS_AND_CONDITIONS);
            f.setArguments(args);
            f.setTargetFragment(this, DIALOG_FRAGMENT);
            f.show(getActivity().getSupportFragmentManager(), Const.FOR_HOW_LONG);
            break;
        case R.id.tvPersonalDetails:
            sfm.saveCurFragment(ServerAPI.PERSONAL_DETAILS, 0);
            ft.replace(android.R.id.content, new PersonalDetailsFragment(), ServerAPI.PERSONAL_DETAILS).addToBackStack(null).commit();
            break;
        case R.id.tvAgreementDetails:
            sfm.saveCurFragment(ServerAPI.AGREEMENT_DETAILS, 0);
            ft.replace(android.R.id.content, new AgreementDetailsFragment(), ServerAPI.AGREEMENT_DETAILS).addToBackStack(null).commit();
            break;
        case R.id.bApply:

            break;
    }

@Override
public void onUpdateData() {
    Log.d(TAG, "Update data");

}

}

DialogFragment:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle args = getArguments();

    ...
}

public Dialog onCreateDialog(Bundle savedInstanceState) {

    ...

        return createDialog(v, R.string.for_how_long, etHowMuch, etForHowLong, etPromotionCode);
    }
    return null;
}
private Dialog createDialog(View view, int titleResID, final EditText howMuchField, final EditText forHowLongField, final EditText promotionCodeField) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(titleResID);
    builder.setView(view);
    builder.setPositiveButton(R.string.set, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {

            doShowProgress();

        }

        private void doShowProgress() {


            ExecuteServerTaskBackground task = new
                    ExecuteServerTaskBackground(getActivity());
                task.action = ServerAPI.GET_TERMS_AND_CONDITIONS;
                onTaskListener listener = new onTaskListener() {

                @Override
                public void onUpdateData() {
                    Log.d(TAG, "Updaaate");

                }
            };
            task.setListener(listener);
            task.args = args;
            task.execute();
        }

    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });
    return builder.create();
}

AsyncTask:

    onTaskListener mListener;

public interface onTaskListener {
    void onUpdateData();
}

public void setListener(onTaskListener listener){
  mListener = listener;
}
public ExecuteServerTaskBackground(Activity activity) {
    this.mActivity = activity;
    this.mContext = activity.getApplicationContext();
}

@Override
protected void onPreExecute() {
    pb = (ProgressBar) mActivity.findViewById(R.id.progressBar1);
    pb.setVisibility(View.VISIBLE);
}

@Override
protected Void doInBackground(Void... params) {
    ServerAPI server = new ServerAPI(mContext);
    if (!args.isEmpty())
        server.serverRequest(action, args);
    else
        server.serverRequest(action, null);
    return null;
}

@Override
protected void onPostExecute(Void result) {
 mListener.onUpdateData();

//There is I just update view but how to update whole variables throughtout callback?        
//                tvNoOfPayments = (TextView) mActivity.findViewById(R.id.tvNoOfPaymentsValue);
//                tvFirstPayment = (TextView) mActivity.findViewById(R.id.tvFirstPaymentValue);
//                tvTotalRepayable = (TextView) mActivity.findViewById(R.id.tvTotalRepayableValue);
//
//                lvPayments = (ListView) mActivity.findViewById(R.id.lvData);
//
//                termsConditionsM = new TermsAndConditionsManager(mContext);
//
//                termsAndConditions = termsConditionsM.getTermsAndConditions();
//
//                int totalPayments = Integer.valueOf(termsAndConditions.get(ServerAPI.NO_OF_PAYMENTS));
//
//                if (totalPayments > 0) {
//                    if (termsAndConditions != null) {
//                        tvNoOfPayments.setText(termsAndConditions.get(ServerAPI.NO_OF_PAYMENTS));
//                        tvFirstPayment.setText(termsAndConditions.get(ServerAPI.FIRST_PAYMENT_DATE));
//                        tvTotalRepayable.setText("£" + termsAndConditions.get(ServerAPI.TOTAL_REPAYABLE));
//                    }
//
//                    paymentsData = termsConditionsM.getpayments();
//
//                    if (paymentsData != null) {
//                        Log.d(TAG, paymentsData.toString());
//
//                        payments = new ArrayList<Payment>();
//
//                        for (int i = 1; i <= totalPayments; i++) {
//                            paymentValues = new Payment();
//                            paymentValues.setPaymentID(Integer.valueOf(paymentsData.get(ServerAPI.PAYMENT_NO + "_" + i)));
//                            paymentValues.setPaymentDate(paymentsData.get(ServerAPI.PAYMENT_DATE + "_" + i));
//                            paymentValues.setPaymentTotalAmount(paymentsData.get(ServerAPI.PAYMENT_TOTAL + "_" + i));
//                            payments.add(paymentValues);
//                        }
//
//                        PaymentAdapter adapter = new PaymentAdapter(mContext, R.layout.custom_loan_item, payments);
//                        lvPayments.setAdapter(adapter);
//                    }
    //             

   }

    pb.setVisibility(View.GONE);
    super.onPostExecute(result);
}

解决方案

Without taking your code in consideration I will post the most essential to make a functional callback.

TestFragment:

public class TestFragment extends Fragment {

    /* Skipping most code and I will only show you the most essential. */    
    private void methodThatStartsTheAsyncTask() {
        TestAsyncTask testAsyncTask = new TestAsyncTask(new FragmentCallback() {

            @Override
            public void onTaskDone() {
                methodThatDoesSomethingWhenTaskIsDone();
            }
        });

        testAsyncTask.execute();
    }

    private void methodThatDoesSomethingWhenTaskIsDone() {
        /* Magic! */
    }

    public interface FragmentCallback {
        public void onTaskDone();
    }
}

TestAsyncTask:

public class TestAsyncTask extends AsyncTask<Void, Void, Void> {
    private FragmentCallback mFragmentCallback;

    public TestAsyncTask(FragmentCallback fragmentCallback) {
        mFragmentCallback = fragmentCallback;
    }

    @Override
    protected Void doInBackground(Void... params) {
        /* Do your thing. */
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        mFragmentCallback.onTaskDone();
    }
}