grade-
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "android.arch.lifecycle:viewmodel:1.1.1"
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
import com.google.gson.Gson;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class Api {
public static final String BASE_URL = "";
private static Retrofit retrofit = null;
Gson gson = new Gson();
public static Retrofit getClient() {
if (retrofit==null) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.connectTimeout(60, TimeUnit.SECONDS);
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.HTTP;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Query;
public interface MyApi {
@Headers("Content-Type: application/json") // annotation that used with POST type request
@POST("api/login") // specify the sub url for our base url
// @HTTP(method = "POST", path = "/index.php/api/user/index_post", hasBody = true)
public Call<String> login(@Body String body);
}
import android.view.View;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class LoginViewModel extends ViewModel {
public MutableLiveData<String> email = new MutableLiveData<>();
public MutableLiveData<String> password = new MutableLiveData<>();
private User user;
private String successMessage = "Login successful";
private String errorMessage = "Email or Password is not valid";
private String toastMessage = null;
private MutableLiveData<User> userMutableLiveData;
public MutableLiveData<User> getUser() {
if (userMutableLiveData == null) {
userMutableLiveData = new MutableLiveData<>();
}
return userMutableLiveData;
}
public void onClick(View view) {
User loginUser = new User(email.getValue(), password.getValue());
userMutableLiveData.setValue(loginUser);
}
}
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import org.json.JSONObject;
import java.util.Objects;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Login extends AppCompatActivity {
private LoginViewModel loginViewModel;
ProgressDialog dialog;
MyApi apiService= Api.getClient().create(MyApi.class);
SharedPreferences pref ;
SharedPreferences.Editor editor ;
private ActivityLoginBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_login);
loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
binding = DataBindingUtil.setContentView(Login.this, R.layout.activity_login);
binding.setLifecycleOwner(this);
binding.setViewModel(loginViewModel);
loginViewModel.getUser().observe(this, new Observer<User>() {
@Override
public void onChanged(@Nullable User loginUser) {
if (TextUtils.isEmpty(Objects.requireNonNull(loginUser).getEmail())) {
binding.email.setError("Enter an E-Mail Address");
binding.email.requestFocus();
}
else if (!loginUser.isEmailValid()) {
binding.email.setError("Enter a Valid E-mail Address");
binding.email.requestFocus();
}
else if (TextUtils.isEmpty(Objects.requireNonNull(loginUser).getPassword())) {
binding.password.setError("Enter a Password");
binding.password.requestFocus();
}
else if (!loginUser.isPasswordLengthGreaterThan5()) {
binding.password.setError("Enter at least 6 Digit password");
binding.password.requestFocus();
}
else {
makeLogin(loginUser.getEmail(),loginUser.password);
}
}
});
}
private void makeLogin(String email,String password) {
try {
dialog=new ProgressDialog(this);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.show();
// System.out.println(user_email);
// System.out.println(user_password);
JSONObject paramObject = new JSONObject();
paramObject.put("email", email);
paramObject.put("password", password);
paramObject.put("token", pref.getString("token",""));
paramObject.put("deviceid", pref.getString("deviceid",""));
System.out.println("data"+paramObject.toString());
Call<String> call = apiService.login(String.valueOf(paramObject));
call.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String>call, @NonNull Response<String> response) {
dialog.dismiss();
System.out.println("data:::"+response.body());
try {
if(response.body()!=null){
JSONObject jsonResponse = new JSONObject(response.body());
String aJsonString = jsonResponse.getString("status");
if (aJsonString.equalsIgnoreCase("1")) {
String data = jsonResponse.getString("data");
JSONObject jsonResponse1 = new JSONObject(data);
Toast.makeText(Login.this, "Login successfull!", Toast.LENGTH_LONG).show();
Intent i = new Intent(Login.this, Dashboard.class);
startActivity(i);
finish();
} else {
Toast.makeText(Login.this, "Error!", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(Login.this, "Error!", Toast.LENGTH_LONG).show();
}
}catch (Exception e){}
}
@Override
public void onFailure(@NonNull Call<String>call, @NonNull Throwable t) {
// Log error here since request failed
System.out.println(t.toString());
dialog.dismiss();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}