How do i use a variable outside the onResponse in Android?

前端 未结 4 1330
我在风中等你
我在风中等你 2020-12-11 11:32

I have created an activity in which i insert some records into a mysql database. I declared a global variable named lastInsertId. When i try to println

4条回答
  •  再見小時候
    2020-12-11 12:11

    I figure it out. I answered this question after about a year, beacuse i saw that this post had a few hundred visitor. Hope my answer will help other feature visitors to get data out from onResponse method. Here is the code:

    String insertUrl = "http://localhost/file.php";
    String lastInsertId;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    
        StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener() {
            @Override
            public void onResponse(String response) {
                lastInsertId = response.toString();
                System.out.println(lastInsertId); // returns the lastInsertId
                callback.onSuccess(lastInsertId);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
    
            }
        }) {
    
            @Override
            protected Map getParams() throws AuthFailureError {
                Map parameters = new HashMap();
    
                // parameters
    
                return parameters;
            }
        };
        requestQueue.add(request);
    }
    
    public interface VolleyCallback{
        void onSuccess(ArrayList dataArrayList);
    }
    

    And this is the code we need inside the Activity.

    public void onResume(){
        super.onResume();
        getString(new VolleyCallback(){
            @Override
            public void onSuccess(String result){
                System.out.println(result); // returns the value of lastInsertId
            }
        });
    }
    

提交回复
热议问题