java,如果我们在用户名和密码中键入错误的字段。它显示登录失败警报,但它正在调用下一个活动。要修这个吗?
此代码用于我的登录活动
我使用了一个意图来调用onPostExecute()
方法中的下一个页面,但它无法正常工作
如果我们在用户名中键入了错误的值&;通过,它将显示登录失败警报,但会调用下一个活动
如何解决这个问题
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);
}
}
# 1 楼答案
您应该使用
onPostExecute
方法。您需要检查doInBackground
方法中的响应代码,并根据结果返回适当的String
。然后在onPostExecute
内检查来自doInBackground
的响应并采取适当的措施# 2 楼答案
onPostExecute
将始终启动下一个活动,而不管String result
的值如何您需要检查该值以确定是否成功登录。还要检查它是否为null,因为它也由
doInBackground
返回