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
Login method in the login activity
makeRequest method in the Login class
Callback class
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
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);
}
});
}
}