简体   繁体   English

Android Volley StringRequest将响应传递给MainActivity

[英]Android Volley StringRequest passing response to MainActivity

Need to get the response in MainActivity 需要在MainActivity中获得响应

MyVolleyClass.java MyVolleyClass.java

public class MyVolleyClass  {
    Context context;

    public String stringResponse()
    {

        StringRequest stringRequest=new StringRequest(Request.Method.POST, URLManager.BASE_URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                //need to return this response to my main activity



            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        MySingleton.getInstance(context).addTorequestque(stringRequest);


        return "";   //whenever a response is got i need to return the response from the server to main activity


    }

}

> MainActivity.java


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//expecting the string returned from the MyVolleyClass.java
        String response=new DataFetcherVolley(getApplicationContext()).dataFetch();
        Toast.makeText(this,response,Toast.LENGTH_LONG).show();   
    }
}
  1. I just need the string response from MyVolleyClass to my MainActivity 我只需要MyVolleyClass对MainActivity的字符串响应
  2. Please make some changes in MyVolleyClass 请在MyVolleyClass中进行一些更改
  3. Thanks in advance 提前致谢

You should use a callback to pass the response from your volley class to the main activity. 您应该使用回调将排球类的响应传递到主要活动。 Please take a look at this SO post from a while back : How can I return value from function onResponse of Volley? 请回想一下这段SO帖子: 如何从Volley的onResponse函数返回值?

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

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