Skip to main content

Post data with retrofit

1 ) Retrofit Client Class

public class RetrofitClient {

    private static final String AUTH = "Basic " + Base64.encodeToString(("belalkhan:123456").getBytes(), Base64.NO_WRAP);

    private static final String BASE_URL = "http://simplifiedlabs.xyz/MyApi/public/";
    private static RetrofitClient mInstance;
    private Retrofit retrofit;


    private RetrofitClient() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(
                        new Interceptor() {
                            @Override                            
                            public Response intercept(Chain chain) throws IOException {
                                Request original = chain.request();

                                Request.Builder requestBuilder = original.newBuilder()
                                        .addHeader("Authorization", AUTH)
                                        .method(original.method(), original.body());

                                Request request = requestBuilder.build();
                                return chain.proceed(request);
                            }
                        }
                ).build();

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();
    }

    public static synchronized RetrofitClient getInstance() {
        if (mInstance == null) {
            mInstance = new RetrofitClient();
        }
        return mInstance;
    }

    public Api getApi() {
        return retrofit.create(Api.class);
    }
}

2 ) Retrofit InterFace

public interface Api {


    @FormUrlEncoded    @POST("createuser")
    Call<DefaultResponse> createUser(
            @Field("email") String email,
            @Field("password") String password,
            @Field("name") String name,
            @Field("school") String school
    );

    @FormUrlEncoded    @POST("userlogin")
    Call<LoginResponse> userLogin(
            @Field("email") String email,
            @Field("password") String password
    );

    @GET("allusers")
    Call<UsersResponse> getUsers();

    @FormUrlEncoded    @PUT("updateuser/{id}")
    Call<LoginResponse> updateUser(
            @Path("id") int id,
            @Field("email") String email,
            @Field("name") String name,
            @Field("school") String school
    );

    @FormUrlEncoded    @PUT("updatepassword")
    Call<DefaultResponse> updatePassword(
            @Field("currentpassword") String currentpassword,
            @Field("newpassword") String newpassword,
            @Field("email") String email
    );

    @DELETE("deleteuser/{id}")
    Call<DefaultResponse> deleteUser(@Path("id") int id);

}



3 ) Sign Up Activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editTextEmail, editTextPassword, editTextName, editTextSchool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextEmail = findViewById(R.id.editTextEmail);
        editTextPassword = findViewById(R.id.editTextPassword);
        editTextName = findViewById(R.id.editTextName);
        editTextSchool = findViewById(R.id.editTextSchool);

        findViewById(R.id.buttonSignUp).setOnClickListener(this);
        findViewById(R.id.textViewLogin).setOnClickListener(this);
    }


    @Override
    protected void onStart() {
        super.onStart();
        if(SharedPrefManager.getInstance(this).isLoggedIn()){
            Intent intent = new Intent(this, ProfileActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }
    }

    private void userSignUp() {
        String email = editTextEmail.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();
        String name = editTextName.getText().toString().trim();
        String school = editTextSchool.getText().toString().trim();

        if (email.isEmpty()) {
            editTextEmail.setError("Email is required");
            editTextEmail.requestFocus();
            return;
        }

        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            editTextEmail.setError("Enter a valid email");
            editTextEmail.requestFocus();
            return;
        }

        if (password.isEmpty()) {
            editTextPassword.setError("Password required");
            editTextPassword.requestFocus();
            return;
        }

        if (password.length() < 6) {
            editTextPassword.setError("Password should be atleast 6 character long");
            editTextPassword.requestFocus();
            return;
        }

        if (name.isEmpty()) {
            editTextName.setError("Name required");
            editTextName.requestFocus();
            return;
        }

        if (school.isEmpty()) {
            editTextSchool.setError("School required");
            editTextSchool.requestFocus();
            return;
        }

        Call<DefaultResponse> call = RetrofitClient
                .getInstance()
                .getApi()
                .createUser(email, password, name, school);


        call.enqueue(new Callback<DefaultResponse>() {
            @Override
            public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
                if (response.code() == 201) {

                    DefaultResponse dr = response.body();
                    Toast.makeText(MainActivity.this, dr.getMsg(), Toast.LENGTH_LONG).show();

                } else if (response.code() == 422) {
                    Toast.makeText(MainActivity.this, "User already exist", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<DefaultResponse> call, Throwable t) {

                Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();

            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buttonSignUp:
                userSignUp();
                break;
            case R.id.textViewLogin:

                startActivity(new Intent(this, LoginActivity.class));

                break;
        }
    }
}

4 ) Sign Up Activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryBackground"
    tools:context=".activities.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/linearLayout"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:text="Sign Up"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Headline"
        android:textColor="@color/colorFormBackground" />

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="@color/colorFormBackground"
        android:orientation="vertical"
        android:padding="10dp">

        <EditText
            android:id="@+id/editTextEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_email"
            android:drawablePadding="5dp"
            android:hint="email"
            android:inputType="textEmailAddress" />

        <EditText
            android:id="@+id/editTextPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_password"
            android:drawablePadding="5dp"
            android:hint="password"
            android:inputType="textPassword" />

        <EditText
            android:id="@+id/editTextName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_name"
            android:drawablePadding="5dp"
            android:hint="name"
            android:inputType="textPersonName" />

        <EditText
            android:id="@+id/editTextSchool"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_school"
            android:drawablePadding="5dp"
            android:hint="school"
            android:inputType="text" />

    </LinearLayout>

    <TextView
        android:id="@+id/textViewLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/linearLayout"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:lineSpacingExtra="7dp"
        android:text="Already have an Account?\nClick to Login"
        android:textAlignment="center"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
        android:textColor="@color/colorFormBackground" />

    <Button
        android:id="@+id/buttonSignUp"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="15dp"
        android:background="@color/colorPrimaryDark"
        android:text="Sign Up"
        android:textAllCaps="false"
        android:textColor="@color/colorFormBackground" />

</RelativeLayout>

5 ) Login Activity

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import net.simplifiedcoding.retrofitandroidtutorial.R;
import net.simplifiedcoding.retrofitandroidtutorial.api.RetrofitClient;
import net.simplifiedcoding.retrofitandroidtutorial.models.LoginResponse;
import net.simplifiedcoding.retrofitandroidtutorial.storage.SharedPrefManager;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {


    private EditText editTextEmail;
    private EditText editTextPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        editTextEmail = findViewById(R.id.editTextEmail);
        editTextPassword = findViewById(R.id.editTextPassword);

        findViewById(R.id.buttonLogin).setOnClickListener(this);
        findViewById(R.id.textViewRegister).setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (SharedPrefManager.getInstance(this).isLoggedIn()) {
            Intent intent = new Intent(this, ProfileActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }
    }

    private void userLogin() {

        String email = editTextEmail.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        if (email.isEmpty()) {
            editTextEmail.setError("Email is required");
            editTextEmail.requestFocus();
            return;
        }

        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            editTextEmail.setError("Enter a valid email");
            editTextEmail.requestFocus();
            return;
        }

        if (password.isEmpty()) {
            editTextPassword.setError("Password required");
            editTextPassword.requestFocus();
            return;
        }

        if (password.length() < 6) {
            editTextPassword.setError("Password should be atleast 6 character long");
            editTextPassword.requestFocus();
            return;
        }

        Call<LoginResponse> call = RetrofitClient
                .getInstance().getApi().userLogin(email, password);

        call.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                LoginResponse loginResponse = response.body();

                if (!loginResponse.isError()) {

                    SharedPrefManager.getInstance(LoginActivity.this)
                            .saveUser(loginResponse.getUser());

                    Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);


                } else {
                    Toast.makeText(LoginActivity.this, loginResponse.getMessage(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buttonLogin:
                userLogin();
                break;
            case R.id.textViewRegister:
                startActivity(new Intent(this, MainActivity.class));
                break;
        }
    }
}
6 ) activitylogin.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryBackground"
    tools:context=".activities.LoginActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/linearLayout"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:text="Login"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Headline"
        android:textColor="@color/colorFormBackground" />

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="@color/colorFormBackground"
        android:orientation="vertical"
        android:padding="10dp">

        <EditText
            android:id="@+id/editTextEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_email"
            android:drawablePadding="5dp"
            android:hint="email"
            android:inputType="textEmailAddress" />

        <EditText
            android:id="@+id/editTextPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_password"
            android:drawablePadding="5dp"
            android:hint="password"
            android:inputType="textPassword" />


    </LinearLayout>

    <TextView
        android:id="@+id/textViewRegister"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/linearLayout"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:lineSpacingExtra="7dp"
        android:text="Don't have an Account?\nClick to Register"
        android:textAlignment="center"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
        android:textColor="@color/colorFormBackground" />

    <Button
        android:id="@+id/buttonLogin"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="15dp"
        android:background="@color/colorPrimaryDark"
        android:text="Login"
        android:textAllCaps="false"
        android:textColor="@color/colorFormBackground" />

</RelativeLayout>

7 ) Model Classes

    I ) DefaultResponse

        public class DefaultResponse {
@SerializedName("error") private boolean err; @SerializedName("message") private String msg; public DefaultResponse(boolean err, String msg) { this.err = err; this.msg = msg; } public boolean isErr() { return err; } public String getMsg() { return msg; } }

    II ) LoginResponse

         public class LoginResponse {
private boolean error; private String message; private User user; public LoginResponse(boolean error, String message, User user) { this.error = error; this.message = message; this.user = user; } public boolean isError() { return error; } public String getMessage() { return message; } public User getUser() { return user; } }

    III ) User

          public class User {
private int id; private String email, name, school; public User(int id, String email, String name, String school) { this.id = id; this.email = email; this.name = name; this.school = school; } public int getId() { return id; } public String getEmail() { return email; } public String getName() { return name; } public String getSchool() { return school; } }
IV ) UsersResponse
public class UsersResponse {
private boolean error; private List<User> users; public UsersResponse(boolean error, List<User> users) { this.error = error; this.users = users; } public boolean isError() { return error; } public List<User> getUsers() { return users; } }


Notes : 
1 ) References : - https://github.com/probelalkhan/Retrofit-Android-Tutorial
2 ) Require Libraries
//App Design
implementation 'com.android.support:design:27.1.0'
//AppCompact
implementation 'com.android.support:appcompat-v7:27.1.1'
// Retrofit & OkHttp 
implementation 'com.squareup.retrofit2:retrofit:2.4.0'implementation 'com.squareup.retrofit2:converter-gson:2.4.0'implementation 'com.android.support:design:27.1.1'implementation 'com.android.support:cardview-v7:27.1.1'
//Recyclerview
implementation 'com.android.support:recyclerview-v7:27.1.1'




Comments

Popular posts from this blog

Android MVVM (Model View ViewModel) Design Pattern

DataBinding Pdf Link:-   https://drive.google.com/open?id=1uL0xK9EktcEWOke5vqUqp-rgqpA1ARR3 DataBinding References : -  https://www.youtube.com/watch?v=v4XO_y3RErI Steps for applying MVVM design pattern to Android Project  1 ) Applying the changes in build.gradle (App Level) file      android {     compileSdkVersion 27     defaultConfig {         applicationId "com.credencys.databindingwithrecyclerview"         minSdkVersion 15         targetSdkVersion 27         versionCode 1         versionName "1.0"         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"     }     buildTypes {         release {             minifyEnabled false             proguardFiles ge...

Complex Retrofit Class With Database

URL:-  http://www.mocky.io/v2/ 5b936d6f33000011002061d3 1 )   Create   RetrofitClient(Base URL Class) import retrofit2.GsonConverterFactory; import retrofit2.Retrofit; public class RetrofitClient { //http://www.mocky.io/v2/5b936d6f33000011002061d3 public static final String API_BASE_URL = "http://www.mocky.io/v2/" ; public static Retrofit retrofit = null ; public static Retrofit getApiClient() { if ( retrofit == null ) { retrofit = new Retrofit.Builder().baseUrl( API_BASE_URL ).addConverterFactory(GsonConverterFactory . create ()).build(); } return retrofit ; } } 2 ) Create Retrofit ApiInterface Class(End URL Class) import com.example.discusit.complexretrofitdemo.model.Data; import retrofit2.Call; import retrofit2.http. GET ; public interface ApiInterface { @GET ( "5b936d6f33000011002061d3" ) Call<Data> getData(); } 3 ) Create Require Model Clas...