简体   繁体   English

我如何在 Android 中使用 onResponse 之外的变量?

[英]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.我创建了一个活动,在其中我将一些记录插入到 mysql 数据库中。 I declared a global variable named lastInsertId .我声明了一个名为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 .当我尝试在onResponse方法内println变量时,工作正常,但是当我尝试在方法外println返回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!谢谢!

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.它们是不同的结果,因为尽管您向本地 HTTP 服务器发出请求,但在设置 lastInsertId 之前,您的最后一个 println 会触发。

You need to think multi-threaded.您需要考虑多线程。 Your HTTP request is running in the background and the UI thread is continuing.您的 HTTP 请求正在后台运行,而 UI 线程仍在继续。 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)请求添加到队列(大概也开始 HTTP 调用)
  4. Prints out lastInsertId (null)打印出 lastInsertId (null)
  5. lastInsertId is set from your response lastInsertId 是根据您的回复设置的
  6. Prints out lastInsertId打印出 lastInsertId

在 onResponse 中使用您的变量的 setter 方法

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.发生这种情况是因为lastInsertId被声明,但从未初始化,然后StringRequest request通过匿名接口使用回调来打印值,这是异步方式,但您的代码正在前进并尝试在此之前打印值发生。

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.你不净额外的setter o getter,你需要验证/该字符串不是空的,或者只在那个callack中打印它的值。

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.希望我的回答能帮助其他功能访问者从 onResponse 方法中获取数据。 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.这就是我们在 Activity 中需要的代码。

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

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

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