Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

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

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 the variable inside the onResponse method, works fine but when i try to println outside the method returns null. I need to use this variable also outside the method. What can be done? Here is my 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<String>() {
        @Override
        public void onResponse(String response) {
            lastInsertId = response.toString();
            System.out.println(lastInsertId); // returns the lastInsertId
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> parameters = new HashMap<String, String>();

            // parameters

            return parameters;
        }
    };
    requestQueue.add(request);
    System.out.println(lastInsertId); // get's null
}

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

They are different results because although you are firing your request to your local HTTP server, your last println fires BEFORE you set the lastInsertId.

You need to think multi-threaded. Your HTTP request is running in the background and the UI thread is continuing. So the order of execution is not in the order the code appears in your sample.

  1. Request queue created
  2. Request created
  3. Request added to queue (presumably starting HTTP call also)
  4. Prints out lastInsertId (null)
  5. lastInsertId is set from your response
  6. Prints out lastInsertId

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...