Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android Simple Login with Retrofit2
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.umairadil.androidlogin.LoginActivity">
<!-- Login progress -->
<ProgressBar
android:id="@+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone"
android:layout_gravity="center"/>
<android.support.v4.widget.NestedScrollView
android:id="@+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:id="@+id/input_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true">
<android.support.v7.widget.AppCompatEditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/prompt_email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/input_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true">
<android.support.v7.widget.AppCompatEditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/prompt_password"
android:imeActionId="6"
android:imeActionLabel="@string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="@+id/email_sign_in_button"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="@string/action_sign_in"
android:textStyle="bold" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
//Retrofit & OkHttp for HTTP Calls
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
implementation 'com.squareup.okhttp3:okhttp:3.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'
}
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import com.umairadil.androidlogin.models.LoginResponse;
import com.umairadil.androidlogin.restclient.RestClient;
import com.umairadil.androidlogin.restclient.RestMethods;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class LoginActivity extends AppCompatActivity {
private String TAG = LoginActivity.class.getSimpleName();
AppCompatEditText email;
AppCompatEditText password;
AppCompatButton loginButton;
TextInputLayout emailInput;
TextInputLayout passwordInput;
ProgressBar progressBar;
NestedScrollView loginForm;
RestMethods restMethods;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Builds HTTP Client for API Calls
restMethods = RestClient.buildHTTPClient();
//Binds UI to Activity
setContent();
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Will validate & call Login API
doLogin();
}
});
}
void setContent() {
loginButton = findViewById(R.id.email_sign_in_button);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
progressBar = findViewById(R.id.login_progress);
loginForm = findViewById(R.id.login_form);
emailInput = findViewById(R.id.input_email);
passwordInput = findViewById(R.id.input_password);
}
/**
* Do login.
* <p>
* <p>This will validate inputs and then do Login.</p>
*/
void doLogin() {
//Check email feild is not empty
if (TextUtils.isEmpty(email.getText().toString())) {
emailInput.setError("No Email Provided!");
return;
}
//Check email format is valid
if (!isValidEmail(email.getText().toString())) {
emailInput.setError("Email is invalid!");
return;
}
//Check password feild is not empty
if (TextUtils.isEmpty(password.getText().toString())) {
passwordInput.setError("No Password Entered!");
return;
}
//TODO Add more validations
//Show loading and call HTTP client's login method
showLoading();
restMethods.login(email.getText().toString(), password.getText().toString()).enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(@NonNull Call<LoginResponse> call, @NonNull Response<LoginResponse> response) {
//Response was successfull
Log.i(TAG, "Response: " + response.body());
hideLoading();
}
@Override
public void onFailure(@NonNull Call<LoginResponse> call, @NonNull Throwable t) {
t.printStackTrace();
//Response failed
Log.e(TAG, "Response: " + t.getMessage());
hideLoading();
}
});
}
/**
* validate your email address format.
*/
public boolean isValidEmail(String email) {
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
private void showLoading() {
progressBar.setVisibility(View.VISIBLE);
loginForm.setVisibility(View.GONE);
}
private void hideLoading() {
progressBar.setVisibility(View.GONE);
loginForm.setVisibility(View.VISIBLE);
}
}
/**
*<p>Modify this class according to your Login API's response JSON.</p>
**/
public class LoginResponse {
String message;
String userName;
String email;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
import android.support.annotation.NonNull;
import android.util.Log;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import static okhttp3.logging.HttpLoggingInterceptor.Level.BODY;
class RestClient {
public static RestMethods buildHTTPClient() {
//TODO Replace with your URL [Must have backslash '/' in end]
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://my-json-server.typicode.com/umair13adil/demo/")
.client(getClient())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return retrofit.create(RestMethods.class);
}
//Create OKHttp Client used by retrofit
private static OkHttpClient getClient() {
return new OkHttpClient.Builder()
.addInterceptor(provideHttpLoggingInterceptor())
.build();
}
//Attach logging intercept to print Logs in LogCat
private static HttpLoggingInterceptor provideHttpLoggingInterceptor() {
HttpLoggingInterceptor httpLoggingInterceptor =
new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(@NonNull String message) {
Log.d("HTTP", message);
}
});
httpLoggingInterceptor.setLevel(BODY);
return httpLoggingInterceptor;
}
}
import retrofit2.Call;
import retrofit2.http.POST;
import retrofit2.http.Query;
/**
* Created by Umair Adil on 10/12/2016.
*/
public interface RestMethods {
//TODO Replace with your API's Login Method
@POST("YOUR_API_METHOD")
Call<LoginResponse> login(@Query("email") String email, @Query("password") String password);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.