MarkoDj
MarkoDj

Reputation: 1

not able to check AsyncTask result

I have a problem that I am not able to check the value of AsyncTask result in order to start new activity if the result is desirable.

Here is my onPostExecute method:

@Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Toast.makeText(LoginActivity.this, s, Toast.LENGTH_SHORT).show();
       }

It toasts string value from php file and it has two possible values, "You are successfully logged in" or "Incorrect email or password". Everything is working fine until I want to check what the toasted message is, because if login is successfull I need to start a new activity.

This is how I tried to do that:

        public void onClick(View v) {
            AttemptLogin login = new AttemptLogin();
            try {
                String res = login.execute("http://10.0.2.2/loginApp.php").get();
                if (res.equals("You are successfully logged in"))
                        startActivity(new Intent(LoginActivity.this,ConnectActivity.class));                                                                               
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

        }

I am totally confused because when I toast res, I get the desirable message, so the problem is with this line,if (res.equals("You are successfully logged in")). The app behaves like this line doesn't exist at all.

I also tried with if(AsyncTask.getStatus() == FINISHED) and then to check AsyncTask result but it didn't help.

I really don't have idea what is going on, can anyone please help me with this?

Upvotes: 0

Views: 41

Answers (1)

Pier Giorgio Misley
Pier Giorgio Misley

Reputation: 5351

AsyncTask has OnPostExecute and OnPreExecute methods. Both of them can call items, variables and methods as if they were normal methods.

So in your onPostExecute you can easily check the result and start your activity using this:

@Override
    protected void onPostExecute(String s) {
        super.onPostExecute();
        try {

            if (s.equals("You are successfully logged in")){
                Intent i = new Intent(LoginActivity.this,ConnectActivity.class);
                startActivity(i); 
            }                                                                              
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        Toast.makeText(LoginActivity.this, s, Toast.LENGTH_SHORT).show();
    }

Upvotes: 1

Related Questions