简体   繁体   English

Android中的服务器端验证:if语句中调用的异步方法

[英]Server-side validation in Android: asynchronous method called in if statement workaround

I was using the Parse API and was trying to implement a change password feature when came across this issue. 遇到此问题时,我正在使用Parse API ,并尝试实现更改密码功能。

I was trying to validate that the user's current password matches their attempted current password (what the user entered into the EditText). 我试图验证用户的当前密码是否与他们尝试的当前密码 (用户在EditText中输入的密码)匹配。

Since the Parse API, doesn't allow access to the user's encrypted password , I'm validating that the user's input matches the current password by trying to log in with the attempted current password and username. 由于Parse API不允许访问用户的加密密码 ,因此我通过尝试使用尝试的当前密码和用户名登录来验证用户输入是否与当前密码匹配。 If the log in was successful, then the attempted current password is correct. 如果登录成功,则尝试输入的当前密码正确。

When the change password button is clicked, I check if the attempted current password matches the actual current password: 单击更改密码按钮时,我检查尝试的当前密码是否与实际的当前密码匹配:

if (mCurrentPassword != null && passwordsMatch(mCurrentPassword)) {
    mCurrentPasswordEditText.setError(getString(R.string.error_incorrect_password));
}

I created a passwordsMatch(String mAttemptedCurrentPassword) method here: 我在这里创建了一个passwordsMatch(String mAttemptedCurrentPassword)方法:

private boolean passwordsMatch(String mCurrentPassword) {
    HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("username", mUser.getUsername());
    params.put( "attemptedCurrentPassword", mCurrentPassword);

    ParseCloud.callFunctionInBackground("validateMatchingPasswords", params, new FunctionCallback<Object>() {
       public void done(Object o, ParseException e) {
           if (e == null) {
             // password match (success)
           } else {
             // password do not match (failure)
           }
       }
    });

}

The above code is incomplete. 上面的代码不完整。 I have a cloud code function, which tries log the user in and responds with a success or error. 我有一个云代码功能,该功能尝试登录用户并以成功或错误响应。 I am having trouble finding a workaround because I don't understand threading that well. 我无法找到解决方法,因为我不太了解线程。

How can I make the if (passwordsMatch) statement wait for the passwordsMatch method to get a result? 如何使if (passwordsMatch)语句等待passwordsMatch方法获得结果?

Edit: 编辑:

For those unfamiliar to Parse, here is what the ParseCloud.callFunctionInBackground function is doing: 对于那些不熟悉Parse的人,这是ParseCloud.callFunctionInBackground函数的作用:

It is essentially an AsyncTask. 它本质上是一个AsyncTask。 It has a callback FunctionCallback , which implements the done method. 它有一个回调FunctionCallback ,它实现了done方法。 The done method is called when ParseCloud.callFunctionInBackground returns a result. ParseCloud.callFunctionInBackground返回结果时,将调用done方法。 It's analogous to the onPostExecute method. 它类似于onPostExecute方法。

The problem is that I have to return a boolean after the asynchronous task is finished. 问题是异步任务完成后,我必须返回一个布尔值。

What you need to do is make a server request (GET/POST) with a pair of username and password. 您需要做的是使用一对用户名和密码发出服务器请求(GET / POST)。 You can use the following code 您可以使用以下代码

new AsyncTask<String, String, String>(){

@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.urloflink.com");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>;
    nameValuePairs.add(new BasicNameValuePair("username", "user"));
    nameValuePairs.add(new BasicNameValuePair("password", "pass"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    } catch (IOException e) {
    // TODO Auto-generated catch block
 }
}

 @Override
 protected void onPostExecute(String result) {
     result = response.getresult(); // a hypothetical function according to your server response format
   // Extract response string from response and check the result
   if(result == "success"){
    // DO something
   }
   else if(result == "failure"){
    // Do something
   }
 }.execute();

This is an asynctask which runs in a separate thread. 这是一个异步任务,在单独的线程中运行。 Hence during this process you can show processing ring or some animation. 因此,在此过程中,您可以显示处理环或某些动画。 The content in doInBackground() runs in background and to make any changes to the UI you can use onPostExecute() block. doInBackground()中的内容在后台运行,并且可以使用onPostExecute()块对UI进行任何更改。

You can use the above code in your password match function as: 您可以在密码匹配功能中使用以下代码:

private boolean passwordsMatch(String mCurrentPassword) {

   new AsyncTask<String,....
    ....
   }.execute();
 }

Make sure that you replace the function response.getResult() with an actual function or some code segment that gives you the result. 确保将函数response.getResult()替换为实际的函数或提供结果的某些代码段。

Usually you don't do it this way. 通常,您不会以这种方式这样做。 You may create a Loader while it's still connecting or parsing and onec it's done you process your stuff in onPostExecute. 您可以在仍处于连接或解析状态的加载器创建一个,然后在onPostExecute中处理您的东西。 There you can disable the loaders view and execute or run your new activity/fragment. 您可以在此处禁用加载程序视图,并执行或运行新的活动/片段。

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

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