在Fragment android中实现AsyncTask

时间:2014-03-17 09:24:14

标签: android android-fragments android-asynctask

首先,我开发了一个Activity,其中json输出被解析并显示在列表中。它运作良好。然后,我将代码从Activity转换为Fragment,如下所示。现在,当AsyncTask执行时,我得到NullPointerException 没有AsyncTask它可以工作。这就是我在线上发表评论的原因,  task.execute();。 数据来自服务器,因此必须使用AsyncTask

有人可以帮我这个吗?

 public class FragmentLoadtransferAddon extends SherlockFragment {
        ProgressBar webservicePG;
         ListAdapter adapter ;
        ListView lv;
    String empid=null;
    ArrayList<HashMap<String, String>> dataList ;
    HashMap<String, String> map;
    private static final String TAG_ITEMNAME = "ItemCode";
    private static final String TAG_QTY = "Quantity";
        public FragmentLoadtransferAddon() {

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

            View rootView = inflater.inflate(R.layout.loadtransferaddon, container, false);
             dataList = new ArrayList<HashMap<String, String>>();
             lv=(ListView) rootView.findViewById(R.id.loadtransfer_form_addon_ListView);
             webservicePG = (ProgressBar) rootView.findViewById(R.id.daystart_form_progressBar1);
               adapter = new SimpleAdapter(getActivity(), dataList,
                        R.layout.rawcurrentstock,
                        new String[] { TAG_ITEMNAME, TAG_QTY}, new int[] {
                                R.id.rawcurrentsock_form_productname,R.id.rawcurrentsock_form_productqty});

    //      
            return rootView;
        }
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onActivityCreated(savedInstanceState);
               AsyncCallWS task = new AsyncCallWS();
    //          // Call execute
    //          task.execute();

                  String json = AddonWebService.invokeDaystartWS(empid,
                            "GetLoadItems");
                    if (json != null) {
                        try {

                            if (json.contains("<!--"))

                                json = json.substring(0, json.indexOf("<!--"));
                            Log.d("Response according to Gettabledata after :: ", " "
                                    + json);
                            jsonObj.getJSONArray("Table");

                            JSONArray tarray = new JSONArray(json);
                            Log.d("tarraytable: ",
                                    " " + tarray);

                            for (int i = 0; i < tarray.length(); i++) {
                                JSONObject jsonChildNode = tarray.getJSONObject(i);

                                String name = jsonChildNode.getString(TAG_ITEMNAME);
                                String qty = jsonChildNode.getString(TAG_QTY);
                                // creating new HashMap
                                map = new HashMap<String, String>();

                                // adding each child node to HashMap key => value
                                map.put(TAG_ITEMNAME, name);
                                map.put(TAG_QTY, qty);

                            dataList.add(map);
                        }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        Log.e("JSON Data", "Didn't receive any data from server!");
                    }
                    lv.setAdapter(adapter);

        }
        private class AsyncCallWS extends AsyncTask<String, Void, Void> {
            @Override
            protected void onPreExecute() {
                webservicePG.setVisibility(View.VISIBLE);
                super.onPreExecute();
            }

            @Override
            protected Void doInBackground(String... params) {
                  String json = AddonWebService.invokeDaystartWS(empid,
                            "GetLoadItems");
                    if (json != null) {
                        try {

                            if (json.contains("<!--"))

                                json = json.substring(0, json.indexOf("<!--"));
                            Log.d("Response according to Gettabledata after :: ", " "
                                    + json);
                            JSONArray tarray = new JSONArray(json);
                            Log.d("tarraytable: ",
                                    " " + tarray);

                            for (int i = 0; i < tarray.length(); i++) {
                                JSONObject jsonChildNode = tarray.getJSONObject(i);

                                String name = jsonChildNode.getString(TAG_ITEMNAME);
                                String qty = jsonChildNode.getString(TAG_QTY);
                                // creating new HashMap
                                map = new HashMap<String, String>();

                                // adding each child node to HashMap key => value
                                map.put(TAG_ITEMNAME, name);
                                map.put(TAG_QTY, qty);

                            dataList.add(map);
                        }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        Log.e("JSON Data", "Didn't receive any data from server!");
                    }
            return null;

            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                webservicePG.setVisibility(View.GONE);


                lv.setAdapter(adapter);

            }
        }

logcat

03-17 12:17:17.087: E/AndroidRuntime(342): java.lang.NullPointerException
03-17 12:17:17.087: E/AndroidRuntime(342):  at com.winwrench.pos.fragments.FragmentLoadtransferAddon$AsyncCallWS.onPreExecute(FragmentLoadtransferAddon.java:110)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.os.AsyncTask.execute(AsyncTask.java:391)
03-17 12:17:17.087: E/AndroidRuntime(342):  at com.winwrench.pos.fragments.FragmentLoadtransferAddon.onActivityCreated(FragmentLoadtransferAddon.java:59)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1508)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.Fragment.performStart(Fragment.java:1521)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:957)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1086)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.FragmentManagerImpl.dispatchStart(FragmentManager.java:1889)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.Fragment.performStart(Fragment.java:1530)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:957)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.os.Handler.handleCallback(Handler.java:587)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.os.Looper.loop(Looper.java:123)
03-17 12:17:17.087: E/AndroidRuntime(342):  at android.app.ActivityThread.main(ActivityThread.java:3683)
03-17 12:17:17.087: E/AndroidRuntime(342):  at java.lang.reflect.Method.invokeNative(Native Method)
03-17 12:17:17.087: E/AndroidRuntime(342):  at java.lang.reflect.Method.invoke(Method.java:507)
03-17 12:17:17.087: E/AndroidRuntime(342):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-17 12:17:17.087: E/AndroidRuntime(342):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-17 12:17:17.087: E/AndroidRuntime(342):  at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

NPE发生在您的代码的以下行:

webservicePG.setVisibility(View.VISIBLE);

您可以在以下行中发起webservicePG

webservicePG = (ProgressBar) rootView.findViewById(R.id.daystart_form_progressBar1);

因此,请确保id = daystart_form_progressBar1

内有loadtransferaddon.xml(区分大小写)

答案 1 :(得分:1)

替换

   adapter = new SimpleAdapter(getActivity(), dataList,
                        R.layout.rawcurrentstock,
                        new String[] { TAG_ITEMNAME, TAG_QTY}, new int[] {
                                R.id.rawcurrentsock_form_productname,R.id.rawcurrentsock_form_productqty});

使用:

   adapter = new SimpleAdapter(container.getContext(), dataList,
                        R.layout.rawcurrentstock,
                        new String[] { TAG_ITEMNAME, TAG_QTY}, new int[] {
                                R.id.rawcurrentsock_form_productname,R.id.rawcurrentsock_form_productqty});

getActivity()返回null,直到onActivityCreated被调用,因此在onCreateView内,您可以通过获取此片段添加到的容器的上下文来引用上下文。