在我对登录进行一些检查之前,我需要完成异步任务的执行。
这是我的异步任务
@Override
protected void onPostExecute(JSONArray jsonArray)
{
JSONObject json_data = null;
for (int i = 0; i < jsonArray.length(); i++) {
try {
json_data = jsonArray.getJSONObject(i);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
for (int j=0; j<jsonArray.length(); j++){
/*allMatrics.add(json_data.getString("matricNos"));
allPasswords.add(json_data.getString("password"));*/
if (user.equals(json_data.get("matricNos")) && pass.equals(json_data.get("password")))
{
ok = true;
System.out.println("hi i am ok");
break;
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Checking ok = "+ ok);
}
我需要在检查其状态之前完成此异步任务,然后继续进行登录身份验证。它应该在登录按钮
的onclick上执行login.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
user = uedit.getText().toString();
pass = pedit.getText().toString();
if (user.equals(""))
{
Toast error = Toast.makeText(LogInScreen.this, "Enter Details", Toast.LENGTH_SHORT);error.show();
}
else
{
final GetMatricNos mat = new GetMatricNos();
mat.execute(new ServerConnector());
// have to finish task before enter user, have to implement logout as well
if ((mat.getStatus().equals(AsyncTask.Status.RUNNING))) - This has to be Status.FINISHED
{
System.out.println(ok);
/* if ((allMatrics.contains(user) && (allPasswords.contains(pass)))) */
if (ok)
{
Intent homescreen = new Intent(LogInScreen.this, HomeScreen.class);
homescreen.putExtra("username", user);
startActivity(homescreen);
}
else
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LogInScreen.this);
alertDialogBuilder.setTitle(Html.fromHtml("<font color='#D41E46'>Invalid Login Details</font>"));
alertDialogBuilder
.setMessage("The login credentials you have entered are invalid. Please try again.")
.setIcon(R.drawable.alert)
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
}
}
});
ActionBar actionBar = getActionBar();
actionBar.hide(); // To hide the actionBar on LoginScreen
}
现在如果我在检查之前没有完成任务,它将不会让我检查我从编辑框中获取的凭据,但是如果我第一次登录它不会进行检查,因为任务按下登录按钮时运行,但如果我登录它第二次通过......?
任何帮助都会非常感激,我在检查之前尝试了task.cancel(true),但这没有帮助......
答案 0 :(得分:1)
如果您的任务需要在执行任何其他操作之前完成执行,那么您必须将必须在onPostExecute
中等待的代码放在任务完成时调用