0

I am calling a webservice using doInBackgroung methode in a service using this code

public class LoginService  {
public int status;
private String _login;
private String _pass;
public HttpResponse response;
public LoginService(String log, String pass) {
    _login = log;
    _pass= pass;
    authenticate();
}
private void authenticate() {
new RequestTask().execute("http://safedrive.url.ph/v1/login?email="+_login+"&password="+_pass);
}class RequestTask extends AsyncTask<String, String, String> {      
@Override
protected String doInBackground(String... uri) {
Log.e("Login","******Login Started************");
HttpClient httpclient = new DefaultHttpClient();
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
    response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
status = statusLine.getStatusCode();
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
e.printStackTrace();
} 
Log.e("reponse", responseString);
return responseString;
}
@Override
protected void onPostExecute(String responseString) {
Log.e("status",""+ status);

//when i execute my code with right values of password and address,status gets the right value (200) and i can loggout it

super.onPostExecute(responseString);
}

Then I call the service in my main activity after a click button

 connectButton.setOnClickListener(
 new OnClickListener() {
 public void onClick(View v) {
address = ADDRESS.getText().toString();
pwd = PASS.getText().toString();
LoginService logService = new LoginService(address,pwd);
Log.e("service", logService.getStatus()+"");// here the value of logService.getStatus() is 0 !!
if (logService.getStatus()==200 )
{
    Intent  intent = new Intent(MainActivity.this,WelcomeActivity.class);
    startActivity(intent);         
}
    else {Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_LONG).show();}
}
});

The value of status is not changed in the main activity so I can't pass to the other activity.

Marya
  • 332
  • 2
  • 16
  • Can you paste the complete code of your LoginService. Anyways what you are trying to acheived can be achieved by binding your activity with the LoginService. Implement ServiceConnection in your activity to get LoginService instance in your activity and call method that contains your aysnctask code and once you have your result use LocalBroadCastManager to send broadcast to your activity sending result of your webservice. Your activity will be registering a reciever too for getting those broadcasts. for binding follow : http://developer.android.com/guide/components/bound-services.html#Binder – Napolean May 09 '14 at 09:07
  • 1
    You're calling your getStatus before your service has had a chance to actually get it with its asynctask. – SvenT23 May 09 '14 at 09:09
  • @Napolean I edited my post so you can see now the complete code of LoginService – Marya May 09 '14 at 09:11
  • @SvenT23 where should I put it then ? – Marya May 09 '14 at 09:12
  • You could put it in a separate method and call that method from the onpostexecute of your asynctask. This way you're always certain that the background task has finished fetching your data. – SvenT23 May 09 '14 at 09:15
  • 1
    Take a look at this: http://stackoverflow.com/questions/9118015/how-to-correctly-start-activity-from-postexecute-in-android – Than May 09 '14 at 09:16
  • 1
    @Marya : Why use an `AsyncTask` in a `Service`? The `AsyncTask` class is designed to provide a background `Thread` (using doInBackground) and to interact with the UI (using `onPostExecute` and other methods). A `Service` doesn't have a UI so using `AsyncTask` is pointless. Either use a `Service` which uses a `Thread` or use `IntentService` which manages its own worker `Thread`. – Squonk May 09 '14 at 09:18

2 Answers2

2

You could start your AsyncTask in your Activity and go to the other Activity from onPostExecute

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
0

Anyways leave that comment as you said service I thought your using AsyncTask inside android's Service.

  1. First Create an interface in your project for listening finish of your service

LoginServiceListener.java

public class LoginService {
    public int status;
    public HttpResponse response;
    private String _login;
    private String _pass;
    private LoginServiceListener mListener = null;

    // Update your constructor
    public LoginService(String log, String pass, LoginServiceListener iListener) {
        _login = log;
        _pass = pass;
        mListener = iListener;
        authenticate();
    }

    private void authenticate() {
        new RequestTask().execute("http://safedrive.url.ph/v1/login?email=" + _login + "&password=" + _pass);
    }


    class RequestTask extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... uri) {
            Log.e("Login", "******Login Started************");
            HttpClient httpclient = new DefaultHttpClient();
            String responseString = null;
            try {
                response = httpclient.execute(new HttpGet(uri[0]));
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    response.getEntity().writeTo(out);
                    out.close();
                    responseString = out.toString();
                    status = statusLine.getStatusCode();
                } else {
                    response.getEntity().getContent().close();
                    throw new IOException(statusLine.getReasonPhrase());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.e("reponse", responseString);
            return responseString;
        }

        @Override
        protected void onPostExecute(String responseString) {
            Log.e("status", "" + status);
            // On service completion you result will be posted back to the activity
            mListener.loginFinished(responseString);
        }
    }
}
  1. Make your activity to register with LoginServiceListener to listen for the service completion events by implementing interface LoginServiceListener

    Make your service call as :

    LoginService service = new LoginService("user", "pass", this);
    

    This will ask you to implement the interface LoginServiceListener and hence add the method

    @Override
    public void loginFinished(String iResponse)
    {
        // This is you response. Now do whatever you want to do.
    
    }
    
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
Napolean
  • 5,303
  • 2
  • 29
  • 35
  • I put LoginService service = new LoginService("user", "pass", this); as you said in the connectButton.setOnClickListener. I get this error The constructor LoginService(String, String, new View.OnClickListener(){}) is undefined – Marya May 09 '14 at 10:28
  • ok just replace this by youractivityname . this LoginService service = new LoginService("user", "pass", MainActivity.this) with your activity name. – Napolean May 09 '14 at 12:38
  • Nothing is happening when I click on the button to go to the next activity – Marya May 09 '14 at 15:21
  • I mean did you logged the program execution. Where it is reaching . Is it reaching your onPostExecute() callback. – Napolean May 09 '14 at 15:26
  • Yes I can loggout the right value in onPostExecute ( here status = 200) but it is not passing to the other class – Marya May 09 '14 at 15:37
  • mListener.loginFinished(responseString); call in onPostExecute() invokes callback you implemented in the activity for this method. have u added this loginFinished() method in your activity by implementing LoginServiceListener interface. – Napolean May 10 '14 at 15:55
  • Yes I puted :public class MainActivity extends Activity implements LoginServiceListener – Marya May 12 '14 at 07:52