0

I am developing an app that logs onto a tomcat server. I am using a HTTP GET request to do so, and upon successful connection, the message is displayed via a buffered stream.

The following code, is used to connect.

public String getInternetData() throws Exception {


BufferedReader in = null;
String data = null;

try {
    HttpClient client = new DefaultHttpClient();
    client.getConnectionManager().getSchemeRegistry().register(getMockedScheme());
    URI website = new URI("https://ts.rks.com:8443/kss/login?username=hydm&password=pw1234"); 
    HttpGet request = new HttpGet();
    request.setURI(website);
    HttpResponse response = client.execute(request);
    response.getStatusLine().getStatusCode();

    in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer sb = new StringBuffer("");
    String l = "";
    String nl = System.getProperty("line.separator");
    while ((l = in.readLine()) != null) {
        sb.append(l + nl);
    }
    in.close();
    data = sb.toString();
    return data;
} finally {
    if (in != null) {
        try {
            in.close();
            return data;
        } catch (Exception e) {
            Log.e("GetMethodLogin", e.getMessage());
        }
    }
}

This is the code that is activated when the user logs in via a login activity. When I go back to the menu screen and try to run another activity that requires the user to be logged in, it says that the user is not logged in.

Is the connection being disconnected when the user moves away from the activity or am I not establishing the connection correctly.

Hydar Roze
  • 85
  • 1
  • 1
  • 4

2 Answers2

0

The connection will not persist when the activity is moved to the background. I cannot tell from your posted code, but I believe you should be using an AsyncTask for this connection. This is coming from my experience pulling HTML source from a link.

This question may answer yours: What to do with AsyncTask in onPause()?

Community
  • 1
  • 1
juicebyjustin
  • 434
  • 7
  • 16
0

There are actually two things you need to change, not just one.

Anything that you need to have persistent across Activities should be done in a Service, not in the code of an Activity.

Second, on recent Android releases, all networking must be done from background threads, rather than the UI thread (there was always a recommendation against UI thread networking, but now it triggers an exception). Just putting the code in a Service does not mean it is in another thread.

So the answer is that you should be doing this using one of the background threading mechanisms, and doing that within a Service.

Chris Stratton
  • 39,853
  • 6
  • 84
  • 117