我有一个登录表单,用于验证用户名或密码是否与我的数据库中的用户名或密码匹配,但我在另一个 java 类中编写了验证代码,如下所示:
AlertDialog dialog;
Context context;
public background (Context context){
this.context = context;
}
@Override
protected void onPreExecute() {
dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Login Status");
}
@Override
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
}
@Override
protected String doInBackground(String... voids) {
String result = "";
String user = voids[0];
String pass = voids[1];
String connStr = "http://xzylrey1.heliohost.org/loginandroid.php";
try {
URL url = new URL(connStr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream ops = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ops, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(user, "UTF-8")
+ "&&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(pass, "UTF-8");
writer.write(data);
writer.flush();
writer.close();
ops.close();
InputStream ips = http .getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ips, "ISO-8859-1"));
String line = "";
while((line = reader.readLine()) != null){
result += line;
}
reader.close();
ips.close();
http.disconnect();
return result;
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
这是主类:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = findViewById(R.id.et_username);
etPassword = findViewById(R.id.et_Password);
btnLogin = findViewById(R.id.btn_Login);
}
public void moveToActivityTwo(){
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
public void loginBtn(View view) {
String user = et_username.getText().toString();
String pass = etPassword.getText().toString();
background bg = new background(this);
bg.execute(user, pass);
moveToActivityTwo();
我尝试将该方法放在 bg.execute 行下方,但它会自动重定向到其他 Activity ,还有其他方法可以做到这一点吗?
您需要将 moveToActivityTwo()
方法移动到 onPostExecute()
方法的末尾。
它看起来像这样:
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
context.moveToActivityTwo();
}
它调用回调模式。
我是一名优秀的程序员,十分优秀!