JustWork
JustWork

Reputation: 1964

Android HttpPost and Multithreading a few issue

I have an Android application that makes a post request to my .NET Web Api. It works fine but I need some updates to provide better service to user. And this leading some problems for me.

I have username, password textboxes and login button in activity_main.xml file.

When user click the login button, I am checking the values, then if they are appropriate I send them to server via my WebRequest.java class.

Here is my problem:

When I am sending these values to server, my main (UI) thread is locking. I wanted to prevent that locking using Thread:

public static WebLoginResponse loginRequest(final String username, final String password) {
    Thread loginThread = new Thread(new Runnable() {
        @Override
        public void run() {
            // making request here.
        }
    });
    loginThread.start();
}

That prevents locking but response returns null. It's clear why is that. Because when I call this method from my MainActivity.java file like:

WebLoginResponse response = WebRequests.loginRequest(username, password);

loginThread running the loginRequest but UI thread came back from loginRequest method and trying to get values of response variable. loginThread has not finished its job yet, that's why response is null.

And this is not the solution of my problem because response always be null.

Finally, I want to do this request but not to locking UI thread.

How can I achieve that?

Thanks.

Upvotes: 0

Views: 103

Answers (2)

Udo Klimaschewski
Udo Klimaschewski

Reputation: 5315

The solution to your problem is a well known pattern in asynchronous programming, named usually promises, futures or delay.

For a general discussion of the pattern, see: Wikipedia: Futures and promises

In Java, have a look at the Future interface, a very good tutorial on this and Java concurrency in general can be found at Lars Vogel's blog.

Upvotes: 1

Tigger
Tigger

Reputation: 9120

You need to perform you web access request on a background thread. Personally, I use an AsyncTask.

Here are a few links:

And here is some sample code which will need work:

private WebLoginTask mWebLoginTask = null;

public static WebLoginResponse loginRequest(final String username, final String password) {
    mWebLoginTask = new WebLoginTask();
    mWebLoginTask.execute();
}

private class WebLoginTask extends AsyncTask<Void, String, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        if (this.isCancelled() == true) { return null; }

        // ..... do your web stuff here .....
    }

    protected void onPostExecute(Void success) {
        // ..... do stuff here when the web stuff is finished ......
    }
}

Upvotes: 0

Related Questions