• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps [Networking]Run callback on main thread

Bruud

Lurker
Sep 7, 2020
1
0
I'm developing an app where I need to have a login screen, so users can login.
At the moment I have the login completely working.
The way I'm doing it is as follows
  • The user presses the login button
  • A second thread (Networking thread) is connecting to a webpage with username and password as the post variables
  • The page then checks if the username and password match with a row in my accounts table
  • The page then outputs a 0 (if successful) a 1 (if not successful)
  • The networking thread reads the result and calls a callback with the result
  • The callback then is called on the ui thread of the app and displays a toast if the login wasn't successful or continues to the next activity
Now comes the part where I'm a bit more unsure about, which is the code. To me it feels like overkill to do it this way (especially the part where I put the calling activity as a variable for the callback to execute the callback on the ui thread).

Login method in the login activity
Java:
private void login() {
    Login login = new Login(this);
    login.makeRequest(new Callback<String>() {
        @Override
        public void onComplete(Result<String> result) {
            if (result instanceof Result.Success) {
                Intent dsp = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(dsp);
            } else {
                Result.Error<String> error = (Result.Error<String>) result;
                Toast.makeText(getApplicationContext(), error.message, Toast.LENGTH_SHORT).show();
            }
        }
    }, usernameEt.getText().toString(), passwordEt.getText().toString());
}

makeRequest method in the Login class
Java:
public void makeRequest(final Callback<String> callback, final String username, final String password) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            final Result<String> result = makeSynchronousRequest(username, password);
            callback.execute(result, callingActivity);
        }
    }).start();
}

Callback class
Java:
public abstract class Callback<T> {

    public abstract void onComplete(Result<T> result);

    public void execute(final Result<T> result, AppCompatActivity callingActivity) {
        callingActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                onComplete(result);
            }
        });
    }
}
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones