PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 21, 2022

[FIXED] How to run Volley in fragment(Navigation Drawer)?

 April 21, 2022     android, android-fragments, android-volley, connection, navigation-drawer     No comments   

Issue

I want to call volley by clicking new item in navigation drawer.
How to run Volley from Fragment? I can run volley easily in activities but it is showing error in "this". i.e.

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

in above code How to run volley in Fragment? in Navigation Drawer?

I am doing this:

 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;
    }

please give me idea.


Solution

before returning the rootView you need to add the following line:

queue.add(stringRequest);

You need to add the request to the RequestQueue.

Also, Volley.newRequestQueue(context) takes a Context as parameter. So you should pass the activity context or the application context.

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

Hope this helps



Answered By - denvercoder9
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing