从Asynctask PostExecute调用片段方法

时间:2018-01-04 15:04:06

标签: android android-fragments methods android-asynctask

我需要有关如何调用类AsyncTask中的片段中的方法的帮助。我一直在寻找类似的问题,我尝试了一些事情,但这对我没用。


问题:

AsyncTask类下载XML并保存一些我感兴趣的标签。接下来在方法onPostExecute中,我必须调用Fragment类中的另一个方法,以使用下载的XML值填充textviews。


代码:

public class XMLParse extends AsyncTask<String, Void, Void> {
    public static String v_temperatura = "", v_humitat = "", v_pressio = "", v_pluja = "", v_hora = "", v_vent = "";
    protected void onPostExecute(Void args) {
                for (int temp = 0; temp < nodelist.getLength(); temp++) {
                    Node nNode = nodelist.item(temp);
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element eElement = (Element) nNode;

                        v_temperatura = getNode("temp", eElement);
                        v_humitat =getNode("hum", eElement);
                        v_pressio = getNode("baro", eElement);
                        v_vent = getNode("windinmph", eElement);
                        v_pluja = getNode("todayraininmm", eElement);
                        v_hora = getNode("time", eElement);

                        if (onAnar.equals("widget")) {
                            WidgetActivity widgetActivity = new WidgetActivity();
                            widgetActivity.omplirTextViews(MyApplication.getAppContext());

                        } else if (onAnar.equals("frgDades")) {
                            /*
                             * Here I need to call the fragment method to 
                             * fill the values in the textviews
                             *
                             * Example: 
                             * DadesActualsFragment dadesActualsFragment = new DadesActualsFragment();
                             * dadesActualsFragment.omplirTextViews();
                            */
                        }

                    }
                }

            }    
}


修改
这是执行AsyncTask的代码:

@Override
    public void onRefresh() {
        Toast.makeText(MyApplication.getAppContext(), "test", Toast.LENGTH_SHORT).show();
        try {
            XMLParse xmlParse = new XMLParse();
            xmlParse.execute("frgDades");

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

        mSwipeRefreshLayout.setRefreshing(false);

    }

Fragment TextViews代码:     omplirTextViews()方法获取为XMLParse类定义的变量的值。

public class DadesActualsFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

        private SwipeRefreshLayout mSwipeRefreshLayout;
        TextView tv_app_temperatura_val, tv_app_humitat_val, tv_app_pressio_val, tv_app_vent_val, tv_app_pluja_val, tv_app_hora_val;

        public DadesActualsFragment() {
            // Required empty public constructor
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View myInflatedView = inflater.inflate(R.layout.fragment_dades_actuals, container, false);

            tv_app_temperatura_val = myInflatedView.findViewById(R.id.tv_app_temperatura_val);
            tv_app_humitat_val = myInflatedView.findViewById(R.id.tv_app_humitat_val);
            tv_app_pressio_val = myInflatedView.findViewById(R.id.tv_app_pressio_val);
            tv_app_vent_val = myInflatedView.findViewById(R.id.tv_app_vent_val);

            // Inflate the layout for this fragment
            return myInflatedView;
        }

    @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            // Implementació del Swipe Refresh
            mSwipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.fragment_dadesActuals_swipeRefreshLayout);
            mSwipeRefreshLayout.setOnRefreshListener(this);
        }

        @Override
        public void onRefresh() {
            Toast.makeText(MyApplication.getAppContext(), "test", Toast.LENGTH_SHORT).show();
            // Executar l'XML parse cada cop que es refresca el widget
            try {
                //XMLParse xmlParse = new XMLParse(dadesActualsFragment);
                //xmlParse.execute("frgDades");
                DadesActualsFragment dadesActualsFragment = new DadesActualsFragment();
                new XMLParse(dadesActualsFragment).execute("frgDades");

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

            mSwipeRefreshLayout.setRefreshing(false);

        }

        public void omplirTextViews() {

            System.out.println("------------------");
            tv_app_temperatura_val.setText(XMLParse.v_temperatura);
            tv_app_humitat_val.setText(XMLParse.v_humitat);
            tv_app_pressio_val.setText(XMLParse.v_pressio);
            tv_app_vent_val.setText(XMLParse.v_vent);

        }
    }

我该怎么办? 问候。

2 个答案:

答案 0 :(得分:0)

你可以这样做,你可以在调用Asynctask构造函数时传递片段实例。请参阅下面的代码。

class WorkerTask extends AsyncTask<Void, Void, Void> {

  private DadesActualsFragment dadesActualsFragment;

  WorkerTask(DadesActualsFragment dadesActualsFragment) {
    this.dadesActualsFragment = dadesActualsFragment;
  }

  @Override
  protected Void doInBackground(Void... params)
  {
    ...
  }

  @Override
  protected void onPostExecute(Void res)
  {
    for (int temp = 0; temp < nodelist.getLength(); temp++) {
            Node nNode = nodelist.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;

                v_temperatura = getNode("temp", eElement);
                v_humitat =getNode("hum", eElement);
                v_pressio = getNode("baro", eElement);
                v_vent = getNode("windinmph", eElement);
                v_pluja = getNode("todayraininmm", eElement);
                v_hora = getNode("time", eElement);

                if (onAnar.equals("widget")) {
                    WidgetActivity widgetActivity = new WidgetActivity();
                    widgetActivity.omplirTextViews(MyApplication.getAppContext());

                } else if (onAnar.equals("frgDades")) {

                     dadesActualsFragment.omplirTextViews();

                }

            }
        }
  }
}

你必须像这样初始化并触发AsyncTak

new WorkerTask(dadesActualsFragment).execute();

答案 1 :(得分:0)

您需要访问片段的当前实例:

class YourTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        ...
    }

    @Override
    protected void onPostExecute(Void args)
    {
        Fragment fragment = getFragmentManager().findFragmentById(R.id.container);
        if (fragment != null && fragment instanceof DadesActualsFragment) {
            ((DadesActualsFragment) fragment).omplirTextViews();
        }
    }
}