0

I need to finish the execution of an async task before I make some checks for my login.

This is my async task

@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);
    }

I need to finish this async task before I Check its status and then go on for my login authentication. It is supposed to be executed on the onclick of the login button

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
    }

Now If I don't finish the task before checking it, it won't let me check the credentials that I am getting from the edit boxes, however first time if I login it doesn't make the check because the task runs when the login button is pressed, but for the second time if I login it goes through...?

Any help would be much appreciated, I tried task.cancel(true) before the check but that doesnt help...

sponturious
  • 131
  • 1
  • 9
  • 1
    If your task is a separate file from your `Activity` then [see this answer about using an interface](http://stackoverflow.com/questions/18517400/inner-class-can-access-but-not-update-values-asynctask/18517648#18517648) and put the code to run after in your callback method. Otherwise, put the code to run when it finishes in `onPostExecute()` – codeMagic Apr 02 '14 at 20:09

1 Answers1

1

If your task needs to finish executing before you do anything else then you must put the code that must wait in your onPostExecute which gets called when the task is finished

tyczj
  • 71,600
  • 54
  • 194
  • 296
  • The problem is I need the "user" value from the edintext box to pass in `protected JSONArray doInBackground(ServerConnector... params) { return params[0].GetMatricNos(user); }`, so If I do it in onPostExecute I don't pass any value to the query i have in php from here. – sponturious Apr 02 '14 at 20:19
  • is the asynctask in a separate file? You can always send what you need in the execute method – tyczj Apr 02 '14 at 20:21
  • No its in the same class – sponturious Apr 02 '14 at 20:24
  • then just keep a class wide variable and then get it in onPostExecute – tyczj Apr 02 '14 at 20:25
  • Thanks I've dealt with that, Thanks for the help but there is a little problem @tyczj how do i get it to stop crashing because of this `protected JSONArray doInBackground(ServerConnector... params) { if (user.equals("") || pass.equals("")) { Toast.makeText(LogInScreen.this, "Please Enter Credentials", Toast.LENGTH_SHORT).show(); return null; } else { return params[0].GetMatricNos(user); } }` I have to return something..? it doesn't take null it just crashes – sponturious Apr 02 '14 at 20:44
  • Cheers for the help guys, I fixed it :) – sponturious Apr 02 '14 at 20:54