代码之家  ›  专栏  ›  技术社区  ›  Nj_96

Android截击StringRequest将响应传递给MainActivity

  •  0
  • Nj_96  · 技术社区  · 7 年前

    需要在MainActivity中获取响应

    我的排球课。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. 我只需要MyVolleyClass对MainActivity的字符串响应
    2. 请在MyVolleyClass中进行一些更改
    3. 提前感谢
    1 回复  |  直到 7 年前
        1
  •  0
  •   Sotiris S. Magionas    7 年前

    您应该使用回调将截击类的响应传递给主活动。请看一下前一段时间的这篇SO帖子: How can I return value from function onResponse of Volley?