此代码用于我的登录 Activity 。
我在onPostExecute()
方法中使用Intent调用下一页,但无法正常工作。
如果我们在用户名和密码中输入错误的值,它会显示登录失败警报,但会调用下一个 Activity 。
如何解决这个问题?
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx) {
context = ctx;
}
@Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://techblog.96.lt/login.php";
if (type.equals("Login")) {
try {
String username = params[1];
String pass = params[2];
URL url = new URL(login_url);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
OutputStream outputStream = httpUrlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(pass, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpUrlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpUrlConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Success");
}
@Override
protected void onPostExecute(String result) {
Intent i = new Intent(context, NewActivity.class);
context.startActivity(i);
alertDialog.setMessage(result);
alertDialog.show();
}
@Override
protected void onProgressUpdate (Void...values)
{
super.onProgressUpdate(values);
}
}
最佳答案
onPostExecute
将始终启动下一个 Activity,无论 String result
的值如何。
您需要检查该值以确定您是否已成功登录。还要检查它是否为 null,因为 doInBackground
也会返回该值
关于java - 如果我们在用户名和密码中输入错误的字段。它显示登录失败警报,但它调用下一个 Activity 。拖车来解决这个问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40081739/