如何运行 Volley in fragment(Navigation Drawer)?

How to run Volley in fragment(Navigation Drawer)?

我想通过点击导航抽屉中的新项目来调用 volley。
如何 运行 从片段中截击? 我可以 运行 在活动中轻松截击,但它在 "this" 中显示错误。即

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);

在上面的代码中 如何在 Fragment 中 运行 凌空抽射? 在导航抽屉中?

我正在这样做:

 public CollegesFragment() {
    }

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


        // Instantiate the RequestQueue.
   RequestQueue queue = Volley.newRequestQueue(this);



        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // Display the first 500 characters of the response string.
                Toast.makeText(getActivity(), response, Toast.LENGTH_LONG).show();
                Log.d("TAG", "hello");
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        return rootView;
    }

请给我意见。

您应该参考 this link 以获取有关使用 RequestQueue 的更多详细信息。

编辑:

public class AppController extends Application {

public static final String TAG = AppController.class
        .getSimpleName();

private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public ImageLoader getImageLoader() {
    getRequestQueue();
    if (mImageLoader == null) {
        mImageLoader = new ImageLoader(this.mRequestQueue,
                new LruBitmapCache());
    }
    return this.mImageLoader;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    // set the default tag if tag is empty
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}
}

在您的片段中使用此方法

/**
 * Making json object request
 * */
private void makeJsonObjReq() {
    showProgressDialog();
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
            Const.URL_JSON_OBJECT, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    msgResponse.setText(response.toString());
                    hideProgressDialog();
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hideProgressDialog();
                }
            }) {

        /**
         * Passing some request headers
         * */
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            return headers;
        }

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", "Androidhive");
            params.put("email", "abc@androidhive.info");
            params.put("pass", "password123");

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq,
            tag_json_obj);

    // Cancelling request
    // ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);       
}

希望对您有所帮助...

在返回 rootView 之前,您需要添加以下行:

queue.add(stringRequest);

您需要将请求添加到 RequestQueue。

此外,Volley.newRequestQueue(context) 将上下文作为参数。所以你应该传递 activity 上下文或应用程序上下文。

RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());

希望对您有所帮助