简体   繁体   English

如何在 android studio 中返回或重用 Volley 库的响应值?

[英]How to return or reuse response value of Volley library in android studio?

public class MainActivity extends AppCompatActivity {
    private static final String url = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=1";
    private static String data ="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        final StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                data=data + response.substring(0);
                Log.d("CODE1",response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this,"Something went wrong",Toast.LENGTH_SHORT).show();
            }
        });

        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(request);

        TextView text = (TextView) findViewById(R.id.text_view);
        text.setText(data);


    }

}

I am trying to use the " response " value of onResponse function at the end of the onCreate function.我正在尝试在 onCreate function 末尾使用 onResponse function 的“响应”值。 As you can see data is assigned to TEXTVIEW but it is not displayed.如您所见,数据已分配给 TEXTVIEW 但未显示。 How can we use the data in response to pass to other data structure and then use for other work?我们如何将响应中的数据传递给其他数据结构,然后用于其他工作?

use like this:像这样使用:

data=data + response.substring(0);
Log.d("CODE1",response);
text.setText(data);

Because, this line(setText) runs before you send request.因为,这条线(setText)在您发送请求之前运行。 You displayed empty data.您显示了空数据。

Move the setText method into onResponsesetText方法移入onResponse

Your code will be like this:您的代码将如下所示:

       TextView text = (TextView) findViewById(R.id.text_view);
final StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d("CODE1",response);
                    text.setText(response);
}
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this,"Something went wrong",Toast.LENGTH_SHORT).show();
            }
        });

        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(request);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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