从AsyncTask向Fragment(Not Activity)发送数据

时间:2015-01-26 06:01:14

标签: android android-asynctask callback

我已将jsonresponse数组数据带到onPostExecute,现在我想将jsonresponse传递给main片段。但是当我尝试它时会出现错误,如图所示。我已经按照这个答案(android asynctask sending callbacks to ui),任何帮助都会很棒。

asynctask class

public class PizzaMenuAsyncTask extends AsyncTask<String, Integer, JSONArray> {
    private OnTaskCompleted listener;
    private JSONArray responseJson = null;
    private Context contxt;
    private Activity activity;
    String email;

    public PizzaMenuAsyncTask(Context context) {

        // API = apiURL;
        this.contxt = context;
    }

    public PizzaMenuAsyncTask(OnTaskCompleted listener) {
        this.listener = listener;
    }

    // async task to accept string array from context array
    @Override
    protected JSONArray doInBackground(String... params) {

        String path = null;
        String response = null;
        HashMap<String, String> request = null;
        JSONObject requestJson = null;
        DefaultHttpClient httpClient = null;
        HttpPost httpPost = null;
        StringEntity requestString = null;
        ResponseHandler<String> responseHandler = null;

        // get the email and password

        try {
            path = "xxxxxxxxx/ItemService.svc/ProductDetails";

            new URL(path);
        } catch (MalformedURLException e) {

            e.printStackTrace();
        }

        try {

            // set the API request
            request = new HashMap<String, String>();
            request.put(new String("CetegoryCode"), "PIZ");
            request.entrySet().iterator();

            // Store locations in JSON
            requestJson = new JSONObject(request);
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(path);
            requestString = new StringEntity(requestJson.toString());

            // sets the post request as the resulting string
            httpPost.setEntity(requestString);
            httpPost.setHeader("Content-type", "application/json");

            // Handles the response
            responseHandler = new BasicResponseHandler();
            response = httpClient.execute(httpPost, responseHandler);

            responseJson = new JSONArray(response);
            // System.out.println("*****JARRAY*****" + responseJson.length());

        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        try {
            responseJson = new JSONArray(response);

        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return responseJson;

    }

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

        listener.onTaskCompleted(responseJson);

    }
}

我有这个界面

public interface OnTaskCompleted {
    void onTaskCompleted(JSONArray responseJson);
}

片段类

public class PizzaFragment extends ListFragment implements OnTaskCompleted {

private QuickReturnListView mListView;
private TextView mQuickReturnView;
private TextView mQuickReturnView1;
private TextView mQuickReturnView2;
private int mQuickReturnHeight;

private static final int STATE_ONSCREEN = 0;
private static final int STATE_OFFSCREEN = 1;
private static final int STATE_RETURNING = 2;
private int mState = STATE_ONSCREEN;
private int mScrollY;
private int mMinRawY = 0;

private TranslateAnimation anim;

GridView grid;
String[] web = { "Pizza1", "Pizza2", "Pizza3", "Pizza4", "Pizza5",
        "Pizza6", "Pizza7", "Pizza8", "Pizza9", "Pizza10", "Pizza11",
        "Pizza12", "Pizza13", "Pizza14", "Pizza15"

};
int[] imageId = { R.drawable.image1, R.drawable.image2, R.drawable.image3,
        R.drawable.image4, R.drawable.image5, R.drawable.image6,
        R.drawable.image7, R.drawable.image8, R.drawable.image9,
        R.drawable.image10, R.drawable.image11, R.drawable.image12,
        R.drawable.image13, R.drawable.image14, R.drawable.image15

};

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

    new PizzaMenuAsyncTask(getActivity()).execute();

    mQuickReturnView = (TextView) view.findViewById(R.id.footer);
    mQuickReturnView1 = (TextView) view.findViewById(R.id.footer1);
    mQuickReturnView2 = (TextView) view.findViewById(R.id.footer2);

    CustomGrid adapter = new CustomGrid(getActivity(), web, imageId);
    grid = (GridView) view.findViewById(R.id.grid);
    grid.setAdapter(adapter);
    return view;
}

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

    mListView = (QuickReturnListView) getListView();
    String[] array = new String[] { "Android1", "Android2", "Android",
            "Android", "Android", "Android", "Android", "Android",
            "Android", "Android", "Android", "Android", "Android",
            "Android", "Android", "Android5" };

    // setListAdapter(new ArrayAdapter<String>(getActivity(),
    // R.layout.menu_list_item, R.id.text1, array));

    mListView.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    mQuickReturnHeight = mQuickReturnView.getHeight();
                    mQuickReturnHeight = mQuickReturnView1.getHeight();
                    mQuickReturnHeight = mQuickReturnView2.getHeight();
                    mListView.computeScroll();
                    // mListView.computeScrollY();
                }
            });

    mListView.setOnScrollListener(new OnScrollListener() {
        @SuppressLint("NewApi")
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {

            mScrollY = 0;
            int translationY = 0;

            if (mListView.scrollYIsComputed()) {
                mScrollY = mListView.getComputedScrollY();
            }

            int rawY = mScrollY;

            switch (mState) {
            case STATE_OFFSCREEN:
                if (rawY >= mMinRawY) {
                    mMinRawY = rawY;
                } else {
                    mState = STATE_RETURNING;
                }
                translationY = rawY;
                break;

            case STATE_ONSCREEN:
                if (rawY > mQuickReturnHeight) {
                    mState = STATE_OFFSCREEN;
                    mMinRawY = rawY;
                }
                translationY = rawY;
                break;

            case STATE_RETURNING:

                translationY = (rawY - mMinRawY) + mQuickReturnHeight;

                System.out.println(translationY);
                if (translationY < 0) {
                    translationY = 0;
                    mMinRawY = rawY + mQuickReturnHeight;
                }

                if (rawY == 0) {
                    mState = STATE_ONSCREEN;
                    translationY = 0;
                }

                if (translationY > mQuickReturnHeight) {
                    mState = STATE_OFFSCREEN;
                    mMinRawY = rawY;
                }
                break;
            }

            /** this can be used if the build is below honeycomb **/
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) {
                anim = new TranslateAnimation(0, 0, translationY,
                        translationY);
                anim.setFillAfter(true);
                anim.setDuration(0);
                mQuickReturnView.startAnimation(anim);
                mQuickReturnView1.startAnimation(anim);
                mQuickReturnView2.startAnimation(anim);
            } else {
                mQuickReturnView.setTranslationY(translationY);
                mQuickReturnView1.setTranslationY(translationY);
                mQuickReturnView2.setTranslationY(translationY);
            }

        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }
    });
}

@Override
public void onTaskCompleted(JSONArray responseJson) {
    // TODO Auto-generated method stub
    try {

        for (int n = 0; n < responseJson.length(); n++) {
            JSONObject object = responseJson.getJSONObject(n);
            if ((object.getString("MainCategoryID")).equals("1")) {
                Log.i("MainCategoryID ", object.getString("ItemCode"));

            }
        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

} 这是我运行应用程序时遇到的错误。我错过了什么 enter image description here

2 个答案:

答案 0 :(得分:0)

应该是

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

    listener.onTaskCompleted(result);

}     

doInBackground返回的JSONArray作为JSONArray结果传递给onPostExecute。

答案 1 :(得分:0)

请注意,您有两个构造函数,如果您调用第一个构建函数来获取PizzaMenuAsyncTask的实例,则在listener.onTaskCompleted(result);方法中调用onPostExecute(JSONArray result)时,您的侦听器将为null。

<强>更新

解决方案是更改您的第一个构造函数,如下所示:

public PizzaMenuAsyncTask(Context context, OnTaskCompleted listener) {

    // API = apiURL;
    this.contxt = context;
    this.listener = listener;
}

然后换行:

new PizzaMenuAsyncTask(getActivity()).execute();

为:

new PizzaMenuAsyncTask(getActivity(), this).execute();