简体   繁体   English

Android在远程MySQL中验证登录

[英]Android Verify login in the remote MySQL

Ok. 好。 I have a remote mySQL set up and the table have two pair values. 我有一个远程mySQL设置,该表有两个对值。 Email: aa, password: aa and Email: bb, password: bb. 电子邮件:aa,密码:aa和电子邮件:bb,密码:bb。

In my main activity, in the loginOnClickListener, I declare a backgroundworker class which extends the AsyncTask class to do the remote connection and verify the login. 在我的主要活动中,在loginOnClickListener中,我声明了一个backgroundworker类,该类扩展了AsyncTask类以进行远程连接并验证登录。 If email and password are correct, the value "Success" would return to String result in the onPostExecute(String result). 如果电子邮件和密码正确,则值“ Success”将在onPostExecute(String result)中返回String result。 I declare a public static String result in the MainActivity. 我在MainActivity中声明了一个公共的静态String结果。 Inside the onPostExecute(String result) of the backgoundworker class 在backgoundworker类的onPostExecute(String result)内部

@Override   
protected void onPostExecute(String result) {
    LoginActivity.get=result;
    delegate.processFinish(result);
    alertDialog.setMessage(result);
    alertDialog.show(); // alertDiaglog can always show the correct message, no "delay"

}

In the MainActivity 在MainActivity中

public class MainActivity extends AppCompatActivity 

    public static String result;




 public void loginButtonListener(){
    button_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String type = "login";
            String email = editText_email.getText().toString();
            String password = editText_password.getText().toString();

            BackgroundWorker worker = new BackgroundWorker(LoginActivity.this);
            worker.delegate=LoginActivity.this;
            worker.execute(type, email, password);
            Toast.makeText(LoginActivity.this,get,Toast.LENGTH_SHORT).show(); // result is null in the first time
        }
    });

}

So the value of result would return to MainActivity and I can verify if the string is "Success" and it will go to another activity once log in success. 因此result的值将返回MainActivity,我可以验证字符串是否为“ Success”,并且成功登录后它将进入另一个活动。 However, when I first sucessfully log in, the value of String result is null in Mainactivity, and then I entered a wrong password, and the result becomes "Success" and then becomes "Fails". 但是,当我第一次成功登录时,在Mainactivity中,字符串结果的值为null,然后输入了错误的密码,结果变为“成功”,然后变为“失败”。

In general, the value of String result in MainActivity is always one step behind the results generated by the button click because of the first null string. 通常,由于第一个空字符串,MainActivity中的String result的值始终比按钮单击生成的结果落后一步。 Anybody has a idea how to verify login or how to solve this issue? 任何人都有一个想法如何验证登录或如何解决此问题?

Since you are starting an Async task, which is asynchronous so naturally the value of result will be null initially. 由于您正在启动异步任务,该任务是异步的,因此自然而然, result值最初将为null。 When postExecute() completes, it will assign result to this variable and then you can have its value. postExecute()完成时,它将结果分配给该变量,然后就可以得到它的值。

Update 更新资料

Declare an interface like which will have onLoginResult method 声明一个类似onLoginResult方法的接口

public interface LoginInterface {

  public void onLoginResult(String result);
}

Make your Activity implement this method 使您的活动实施此方法

public class MainActivity extends AppCompatActivity implements LoginInterface {

  @Override
  public void onLoginResult(String result) {

  }



 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MyAsyncTask task = new MyAsyncTask(this);
}

}

Assuming your AsyncTask is MyAsyncTask 假设您的AsyncTask是MyAsyncTask

class MyAsyncTask extends AsyncTask<String, Void, Boolean> {

    private LoginInterface loginInterface;

     //Change the number of arguments according to your requirements.
    AsyncTask(LoginInterface loginInterface) {
    this.loginInterface  = loginInterface;
    }

    @Override
    protected Boolean doInBackground(String... params) {

        // Some code

        return true;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        loginInterface.onLoginResult(result);
    }
}

Now once postExecute complete it will make a call to your MainActivity's onLoginResult with the actual result. 现在,一旦postExecute完成,它将使用实际结果调用MainActivity的onLoginResult Here you can do whatever stuff you want like starting an activity. 在这里,您可以做任何想做的事情,例如开始一项活动。

I striped down what you are trying to do to a Button and an inner AsyncTask class. 我将您要尝试执行的操作简化为一个Button和一个内部AsyncTask类。 Take note that the Toast and starting the new Activity are in the onPostExecute because the AsyncTask runs asynchronously, which means, it could return at any point in the future, not immediately after you click the button or call .execute() . 请注意,Toast和开始新的Activity在onPostExecute因为AsyncTask异步运行,这意味着它可以在将来的任何时候返回,而不是在单击按钮或调用.execute()之后立即返回。

I don't have a SQL database to test against, so I just slept the running thread for a second to simulate a network operation. 我没有要测试的SQL数据库,因此我只是将正在运行的线程睡眠了一秒钟以模拟网络操作。

It's also worth noting that by making the inner class, you can easily call startActivity and finish because you are still within scope of the current activity Context . 还值得注意的是,通过创建内部类,您可以轻松调用startActivityfinish因为您仍处于当前活动Context范围之内。

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);

        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String email = "test@test.com"; // blah, blah .getText()
                String password = "password"; // blah, blah .getText()

                new LoginTask().execute("type?", email, password);
            }
        });
    }

    class LoginTask extends AsyncTask<String, Void, Boolean> {

        private String email;

        @Override
        protected Boolean doInBackground(String... params) {
            String type = params[0];
            this.email = params[1]; // save the email, if you want
            String password = params[2];

            // Do your database stuff
            try {
                // Simulate some long running operation
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
                return false;
            }

            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            Toast.makeText(getApplicationContext(), String.valueOf(result), Toast.LENGTH_SHORT).show();

            if (result) {
                Intent i = new Intent(MainActivity.this, DashboardActivity.class);
                i.putExtra("email", this.email); // send some arguments to the next activity
                startActivity(i); // You have logged-in, move to the next screen
                finish(); // Kill the login activity
            } 
        }
    }
}

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

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