3

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!

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

4 Answers4

2

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
Knossos
  • 15,802
  • 10
  • 54
  • 91
  • The problem isn't the code as such. It is in the logic of your program. If you want to work with the ID, you should write a function to call from onResponse. – Knossos Nov 24 '15 at 14:39
  • It is not possible to do, without knowing the purpose of the App. Why the ID is even needed, for example. You will need to figure out that part out on your own. – Knossos Nov 24 '15 at 15:01
  • I tried to figure it out for more than 4 hours but no luck. I read tens of posts and no one fits my requirements. All that i want is the `lastInsertId ` variable to have the same the value everywhere, not only in the `onResponse` method. I know that the variable is obtained asynchronously but how can i achieve that? – Alex Mamo Nov 24 '15 at 18:46
  • 1
    It /is/ reachable everywhere (in your class). It just isn't /set/ until your onResponse callback is reached. If this value is critical to the rest of your entire Activity, then you need to apply a ProgressDialog or similar in order to halt the users progress, whilst also showing that the App is doing something. – Knossos Nov 25 '15 at 06:38
0

user a setter method of your variable inside onResponse

Booble
  • 11
0

This is happening because the lastInsertId is getting declared, but never initialized, then the StringRequest request is using a callback through anonym interfaces to print the value, that is happening asynchronous way, but your code is going forward and tryinh to print the value before that happens.

you don net extra setters o getters, you need to validate / that the string is not empty, OR only print its value inside that callack.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

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<String>() {
        @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<String, String> getParams() throws AuthFailureError {
            Map<String, String> parameters = new HashMap<String, String>();

            // parameters

            return parameters;
        }
    };
    requestQueue.add(request);
}

public interface VolleyCallback{
    void onSuccess(ArrayList<Data> 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
        }
    });
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193