简体   繁体   English

使用AsyncTask来自服务器的第一响应始终为null

[英]First response from server always null with AsyncTask

I've setup a MySql server with a RESTful api to handle my login/signup system for my android app. 我已经使用RESTful API建立了MySql服务器,以处理我的Android应用程序的登录/注册系统。

I'm creating an ASyncTask to handle the signup POST request, the server should return a JSON object telling us whether it was successful or not. 我正在创建一个ASyncTask来处理注册POST请求,服务器应返回一个JSON对象,告诉我们是否成功。 When I input valid details and register on my Android app, the first response in onPostExecute is null. 当我输入有效的详细信息并在我的Android应用上注册时,onPostExecute中的第一个响应为null。 I press the button again and it is correct. 我再次按下按钮,这是正确的。 What could I be doing wrong? 我可能做错了什么?

private class PostAndReadResponseTask extends AsyncTask<Account, Void, String> {
    @Override
    protected String doInBackground(Account... accounts) {
        final Account thisAccount = accounts[0];
        RequestQueue requestQueue = Volley.newRequestQueue(RegisterActivity.this);
        final String signupURL = "http://localhost:8080/fitnessTrack/api.php?apicall=signup";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, signupURL, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                responseJSON = response;
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Volley Error:", error.getMessage());
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("username", thisAccount.getUsername());
                params.put("password", thisAccount.getPassword());
                params.put("email", thisAccount.getEmail());
                params.put("firstname", thisAccount.getFirstName());
                return params;
            }
        };
        requestQueue.add(stringRequest);
        return responseJSON;
    }

    @Override
    protected  void onPostExecute(String result) {
        System.out.println(result);
    }
}

FYI: I edited the URL to say localhost, even though I'm using my own external IP. 仅供参考:即使我使用自己的外部IP,我也将URL编辑为localhost。 Even when the response is null, the database does update with the signup data. 即使响应为空,数据库也会使用注册数据进行更新。

The responseJSON is only updated here responseJSON仅在此处更新

@Override
public void onResponse(String response) { 
    responseJSON = response; // update UI using responseJSON in here
}

so it won't be ready until that method is called with the response. 因此,只有在响应中调用该方法后,它才能准备就绪。 Try printing in there and it should work 尝试在其中打印,它应该可以工作

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

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