简体   繁体   中英

android volley simple http request

New to volley. Quick question. I can get volley simple HTTP request to work fine when placed in onCreate Is it possible to put the request into a separate class?

Android studio cannot resolve "stringRequest" in this example. Help much appreciated...

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Retriever go = new Retriever();
        go.queue.add(stringRequest);
    }

public class Retriever {


    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
    String url = "http://www.google.com";

    public StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // mTextView.setText("Response is: " + response.substring(0, 500));
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // mTextView.setText("That didnt work!");
        }

    });

}

}

Since your stringRequest variable is in the scope of Retriever class, its visibility is contained in that class only. That's why you are getting that error.

It will go away if you write

go.queue.add(go.stringRequest);

as you are referencing the object from the instance of its class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM