【问题标题】:How to run Volley in fragment(Navigation Drawer)?如何在片段(导航抽屉)中运行 Volley?
【发布时间】:2015-04-20 09:13:51
【问题描述】:

我想通过单击导航抽屉中的新项目来调用 volley。
如何从 Fragment 运行 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;
    }

请给我意见。

【问题讨论】:

    标签: android android-fragments connection android-volley navigation-drawer


    【解决方案1】:

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

    queue.add(stringRequest);
    

    您需要将请求添加到 RequestQueue。

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

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

    希望对你有帮助

    【讨论】:

    • 非常感谢这个对我有用。只是我得到了需要的东西。再次感谢。
    • 建议使用 ApplicationContext 而不是 ActivityContext。
    • @MehrdadSComputer 这取决于。如果您有一些特定于活动/片段的网络请求,则应提供活动上下文。如果网络请求应该在活动破坏中幸存下来,则传递应用程序上下文。顺便说一句,我不建议使用凌空。使用改造
    【解决方案2】:

    您应该参考 this 链接以了解有关使用 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);       
    }
    

    希望对你有帮助……

    【讨论】:

    • 我想不通。我只是想通过 volley 中的片段而不是 MainActivity 来抽象数据。
    • 您的响应数据是什么,String 或 JSONObject 或 JSONArray 或 XML?
    • 它的 JsonObject 我想从 web 获取。我只想在 toast 中显示该数据,我可以通过使用与 googledevelopers 相同的方法轻松显示在活动中,但在片段中我不能:(
    • 让我检查一下。我正在执行,如果有任何事情我会通知你。谢谢!!!
    • 非常感谢我明白了谢谢
    猜你喜欢
    • 1970-01-01
    • 2018-01-16
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 2014-01-17
    相关资源
    最近更新 更多