Tuesday, 31 May 2016

PlaceAutocompleteIntent and PlaceAutocompleteFragment Example Android



Step 1:

add in android app gradle:

compile 'com.google.android.gms:play-services-nearby:8.4.0
'compile 'com.google.android.gms:play-services-location:8.4.0'

First of all need to API key and Enable Google Place API to search and get place details. Add your API key to your app manifest ,need to replacing YOUR_API_KEY with your own API key:
<application>
  ...
  <meta-data
      android:name="com.google.android.geo.API_KEY"
      android:value="YOUR_API_KEY"/>
</application>

Step 2:

PlaceAutocompleteIntent Example


private final static int PLACE_AUTOCOMPLETE_REQUEST_CODE = 12;
LatLng latlong;

call this mehod where you want to get auto complete location:
callPlaceAutocompleteActivityIntent();



 private void callPlaceAutocompleteActivityIntent() {
        try {
            Intent intent =
      new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                            .build(this);
            startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
//PLACE_AUTOCOMPLETE_REQUEST_CODE is integer for request code       
 } catch (GooglePlayServicesRepairableException | 
                   GooglePlayServicesNotAvailableException e) {
            // TODO: Handle the error.        }

    }


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Place place = PlaceAutocomplete.getPlace(this, data);
            latlong = place.getLatLng();
            txtlocation.setText(place.getAddress().toString());
        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(this, data);
        } else if (requestCode == RESULT_CANCELED) {

        }
    }
}





PlaceAutocompleteFragment Example


<fragment
  android:id="@+id/place_autocomplete_fragment"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
  />


Java:
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
            getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);


AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
        .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
        .build();
autocompleteFragment.setFilter(typeFilter);

autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
    @Override
    public void onPlaceSelected(Place place) {
        // TODO: Get info about the selected place.
        Log.i(TAG, "Place: " + place.getName());//get place details here
    }

    @Override
    public void onError(Status status) {
        // TODO: Handle the error.
        Log.i(TAG, "An error occurred: " + status);
    }
});

Customize Date



todayMonth = (TextView) findViewById(R.id.todayMonth);
todayDay = (TextView) findViewById(R.id.todayDay);
today = (TextView) findViewById(R.id.today);

tommorowyMonth = (TextView) findViewById(R.id.tommorowyMonth);
tommorow = (TextView) findViewById(R.id.tommorow);
tomorrowTxt = (TextView) findViewById(R.id.tomorrowTxt);

lastMonth = (TextView) findViewById(R.id.lastMonth);
lastDay = (TextView) findViewById(R.id.lastDay);
last = (TextView) findViewById(R.id.last);

Date d = new Date();
getdate(d, 1);




public void getdate(Date d, int id) {
    DateFormatSymbols dfs = new DateFormatSymbols();
    String[] months = dfs.getMonths();
    SimpleDateFormat mdformat = new SimpleDateFormat("dd / MM / yyyy ");
    String strDate = mdformat.format(d);


    String dateStr[] = getdateVal(strDate);
  

    if (id == 1) {
        todayMonth.setText(months[d.getMonth()]);
        todayDay.setText(dateStr[0]);

        Calendar calendar = Calendar.getInstance();

        int thisYear = calendar.get(Calendar.YEAR);
        int thisMonth = calendar.get(Calendar.MONTH);
        int thisDay = calendar.get(Calendar.DAY_OF_MONTH);
        Date dd = new Date(thisYear, thisMonth, thisDay + 1);
        date[0]=thisYear+"-"+thisMonth+"-"+thisDay;
        getdate(dd, 2);

    } else if (id == 2) {

        tommorowyMonth.setText(months[d.getMonth()]);
        tommorow.setText(dateStr[0]);
        tomorrowTxt = (TextView) findViewById(R.id.tomorrowTxt);
        tomorrowTxt.setText("TOMORROW");

        Calendar calendar = Calendar.getInstance();

        int thisYear = calendar.get(Calendar.YEAR);
        int thisMonth = calendar.get(Calendar.MONTH);
        int thisDay = calendar.get(Calendar.DAY_OF_MONTH);
        Date dd = new Date(thisYear, thisMonth, thisDay + 2);
        date[1]=thisYear+"-"+thisMonth+"-"+thisDay;
        getdate(dd, 3);


    } else if (id == 3) {

        lastMonth.setText(months[d.getMonth()]);
        lastDay.setText(dateStr[0]);

        Calendar calendar = Calendar.getInstance();

        int thisYear = calendar.get(Calendar.YEAR);
        int thisMonth = calendar.get(Calendar.MONTH);
        int thisDay = calendar.get(Calendar.DAY_OF_MONTH);
        Date dd = new Date(thisYear, thisMonth, thisDay + 1);
        String dayOfTheWeek = (String) DateFormat.format("EEEE", dd);
        date[1]=thisYear+"-"+thisMonth+"-"+thisDay;
        last.setText(dayOfTheWeek);
    }
}

public String[] getdateVal(String date) {
    String str[] = date.split("/");
    return str;

}

Monday, 30 May 2016

LinkedIn Iimplementation and Getting User Details with Android


Step 1: add dependencies in app gradle

compile project(':linkedin-sdk')


Step 2: 


public static final int LINKEDIN_SELECT = 1;
int mScialCode=1;

public void login_linkedin() {
    LISessionManager.getInstance(getApplicationContext()).init
       (this, buildScope(), new AuthListener() {
        @Override        public void onAuthSuccess() {
            getLinkedInProfileData();
            
        }

        @Override        public void onAuthError(LIAuthError error) {

           
        }
    }, true);
}


private void getLinkedInProfileData() {
    progress.show();
    String url = 
"https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,email-address)";

    APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
    apiHelper.getRequest(this, url, new ApiListener() {
        @Override        public void onApiSuccess(ApiResponse apiResponse) {
            // Success!            String rr = "";
            JSONObject res = apiResponse.getResponseDataAsJson();
            Log.d("profile info", apiResponse.getResponseDataAsString());
            try {
                rr = res.getString("emailAddress");
                res.getString("lastName");
                email_id = res.getString("emailAddress");
                f_name = res.getString("firstName");
                l_name = res.getString("lastName");
                String id = res.getString("id");
                personPhotoUrl = res.getString("pictureUrl");
                sph.setString("PROFILEPIC", personPhotoUrl);
                sph.setBoolean("ISSOCIAL", true);
                isSocial = true;
                socialMeadiaType = 3;
                SinUpClient(f_name, l_name, "", email_id, "", "", "");

            } catch (JSONException e) {
       
                progress.dismiss();
            }
            progress.dismiss();
        }

        @Override        public void onApiError(LIApiError liApiError) {
            // Error making GET request!            progress.dismiss();
        }

    });
}


private static Scope buildScope() {
    return Scope.build(Scope.R_BASICPROFILE, Scope.W_SHARE, Scope.R_EMAILADDRESS);
}


@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
 
     if (mScialCode == LINKEDIN_SELECT)
        LISessionManager.getInstance(getApplicationContext())
       .onActivityResult(this, requestCode, resultCode, data);
    else {
    }
}

Saturday, 28 May 2016

Generating KeyHases and SHA1 for Android


Step 1:

You need to download openssl first-

you can download openssl form given link below-

https://code.google.com/archive/p/openssl-for-windows/downloads

Step 2:

JDK must be installed in your computer else you download first and set the
path in environment variable because keytool is available in jdk/bin/keytool

Step3:

and finaly you can run given command from cmd

you have to put actually the path to your openssl folder that you have downloaded. Your actual command should look like:

keytool -exportcert -alias androiddebugkey -keystore C:\Users\Vijay\.android\debug.keystore | "E:\openssl\bin\openssl.exe" sha1 -binary | "E:\openssl\bin\openssl.exe" base64


For Generating SHA1

Just open Gradle Projects in android studio

and goto app/task/android/ and just double click over signingReport  and check your console
you will get SHA1








Friday, 27 May 2016

Example Login with google and getting profile data Android



Step 1:
use in app gradle-
compile 'com.google.android.gms:play-services-plus:8.4.0'


Step 2:

Entry in AndroidManifest

<meta-data    android:name="com.google.android.geo.API_KEY"    
android:value="AIzaSyDLJ4gqadVVrjTLM1x-RfsCU_QQ_olY-N0" />

and past the google-services.json in app 

Step 3:
And open Activity where you want to implemet and 
just implemet GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,View.OnClickListener 

Data members .......
private GoogleApiClient mGoogleApiClient;
private ConnectionResult mConnectionResult;
private static final int RC_SIGN_IN = 0;


private void signInWithGplus() {

    if (!mGoogleApiClient.isConnecting()) {
        mSignInClicked = true;
        mGoogleApiClient.connect();

        Log.e("", " isConnected is :: " + isConnected);
        if (isConnected == false) {
            resolveSignInError();
            updateUI(true);
        } else if (isConnected == true) {
            getProfileInformation();
          
            updateUI(true);
        }
    } else {

        //  Toast.makeText(this, "User is not connected!", Toast.LENGTH_LONG).show();    }

}

private void resolveSignInError() {
    if (mConnectionResult.hasResolution()) {
        try {
            mIntentInProgress = true;
            mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
        } catch (IntentSender.SendIntentException e) {
            mIntentInProgress = false;
            mGoogleApiClient.connect();
        }
    }
}


private void updateUI(boolean isSignedIn) {
    if (isSignedIn) {
        // btnSignIn.setVisibility(View.GONE);       
 // authButton.setVisibility(View.GONE);        
// btnSignOut.setVisibility(View.VISIBLE);    
} else {
        // btnSignIn.setVisibility(View.VISIBLE);      
  // authButton.setVisibility(View.VISIBLE);       
 // btnSignOut.setVisibility(View.GONE);    }
}


public void signOutFromGplus() {
  if (mGoogleApiClient.isConnected()) {
        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
        mGoogleApiClient.disconnect();
        //  mGoogleApiClient.connect();       
          isConnected = false;
    }
}

@SuppressWarnings("unused")
private void revokeGplusAccess() {
    if (mGoogleApiClient.isConnected()) {
        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
        Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient).
setResultCallback(new ResultCallback<Status>() {
            @Override            public void onResult(Status arg0) {
                // Log.e(TAG, "User access revoked!");              
  mGoogleApiClient.connect();
                updateUI(false);
            }
        });
    }
}

public static String personPhotoUrl = null;

// Fetching user's information name,email , profile pic
  private void getProfileInformation() {
    try {
        Log.e("", " get profile information called..");
        if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
            Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);

            String personName = currentPerson.getDisplayName();
            String dob = currentPerson.getBirthday();

            personPhotoUrl = currentPerson.getImage().getUrl();
            String acId=currentPerson.getId();
            sph.setString("PROFILEPIC", personPhotoUrl);
            sph.setBoolean("ISSOCIAL", true);
            String personGooglePlusProfile = currentPerson.getUrl();
            String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
            int gender = currentPerson.getGender();
            Log.e("TaG", "Name: " + personName + ", plusProfile: " 
personGooglePlusProfile + ", email: " + email + ", gender : " + gender);


            try {
                if (mSignInClicked) {
                    socialMeadiaType = 2;
                    loadingDialog.dismiss();
                 // Go for next Activity>............
               }
            } catch (Exception e) {
                Toast.makeText(this, "User Already Exist!", Toast.LENGTH_LONG).show();
                loadingDialog.dismiss();
            }

        } else {
            Toast.makeText(getApplicationContext(), "Person information is null"
          Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
        loadingDialog.dismiss();
        // Tracking exception
    }
}

protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
    //EasyTracker.getInstance(this).activityStart(this);}

protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
    //EasyTracker.getInstance(this).activityStop(this);}


boolean isConnected = false;

boolean isFirstLogInGoogle = true;

@Overridepublic void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub
    mSignInClicked = false;
    isConnected = true;
    // Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
    updateUI(true);

    if (isFirstLogInGoogle == true) {

        isFirstLogInGoogle = false;

        getProfileInformation();
    }
}

@Overridepublic void onConnectionSuspended(int i) {
    mGoogleApiClient.connect();
    isConnected = false;
    updateUI(false);
}


public void googleLogin() {

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Plus.API)
            .addScope(Plus.SCOPE_PLUS_LOGIN).build();
    if (sph.getBoolean("ISLOGIN", false) == false)
        signOutFromGplus();
}

@Overridepublic void onConnectionFailed(ConnectionResult result) {
    // TODO Auto-generated method stub    if (!result.hasResolution()) {

        return;
    }
    if (!mIntentInProgress) {
        mConnectionResult = result;
        if (mSignInClicked) {
            resolveSignInError();
        }
    }
}


@Overridepublic void onClick(View v) {
    int id=v.getId();

    switch (id)
    {
        case R.id.txtLoginWithGoogle:
            loadingDialog.show();
            signInWithGplus();
            break;

      
    }
}

@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
 
}


Tuesday, 24 May 2016

Customize TimePicker to NumberPicker and set Color



@Overridepublic void onAttachedToWindow() {
    super.onAttachedToWindow();
    try {
        Class<?> classForid = Class.forName("com.android.internal.R$id");

        Field field = classForid.getField("minute");

        NumberPicker mMinuteSpinner = (NumberPicker) time_picker                .findViewById(field.getInt(null));
        mMinuteSpinner.setMinValue(0);
        mMinuteSpinner.setMaxValue((60 / TIME_PICKER_INTERVAL) - 1);
        List<String> displayedValues = new ArrayList<String>();
        for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
            displayedValues.add(String.format("%02d", i));
        }

        mMinuteSpinner.setDisplayedValues(displayedValues
                .toArray(new String[0]));

        setNumberPickerTextColor(mMinuteSpinner, getResources().getColor(R.color.black));

        //for Hours....................
        displayedValues.clear();
        field = classForid.getField("hour");

        mMinuteSpinner = (NumberPicker) time_picker                .findViewById(field.getInt(null));
        mMinuteSpinner.setMinValue(0);
        mMinuteSpinner.setMaxValue((60 / TIME_PICKER_INTERVAL) - 1);
        displayedValues = new ArrayList<String>();
        for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
            displayedValues.add(String.format("%02d", i));
        }

        mMinuteSpinner.setDisplayedValues(displayedValues
                .toArray(new String[0]));
        setNumberPickerTextColor(mMinuteSpinner, getResources().getColor(R.color.black));

        // for Seconds.............

        displayedValues.clear();

        field = classForid.getField("amPm");
        mMinuteSpinner = (NumberPicker) time_picker                .findViewById(field.getInt(null));
        setNumberPickerTextColor(mMinuteSpinner, getResources().getColor(R.color.black));
    } catch (Exception e) {
        e.printStackTrace();
    }
}


public static boolean setNumberPickerTextColor(NumberPicker numberPicker, int color) {
    final int count = numberPicker.getChildCount();
    for (int i = 0; i < count; i++) {
        View child = numberPicker.getChildAt(i);
        if (child instanceof EditText) {
            try {
                Field selectorWheelPaintField = numberPicker.getClass()
                        .getDeclaredField("mSelectorWheelPaint");
                selectorWheelPaintField.setAccessible(true);
                ((Paint) selectorWheelPaintField.get(numberPicker)).setColor(color);
                ((EditText) child).setTextColor(color);
                numberPicker.invalidate();
                return true;
            } catch (NoSuchFieldException e) {
                Log.w("setNumberPickerTextColor", e);
            } catch (IllegalAccessException e) {
                Log.w("setNumberPickerTextColor", e);
            } catch (IllegalArgumentException e) {
                Log.w("setNumberPickerTextColor", e);
            }
        }
    }
    return false;
}

Wednesday, 18 May 2016

BaseAdaptor Example Android


 */public class ProfessionalListAdaptor extends BaseAdapter {

    List<ProfessionalResultModel> prList;
    Context mContext;
    ViewHolderItem viewHolder;

    public ProfessionalListAdaptor(Context context, List<ProfessionalResultModel> aList) {
        this.prList = aList;
        this.mContext = context;
    }

    @Override    
     public int getCount() {
        return prList.size();
    }

    @Override   
      public Object getItem(int position) {
        return prList.get(position);
    }

    @Override   
     public long getItemId(int position) {

        return position;
    }

    @Override    
    public View getView(final int position, View convertView, ViewGroup parent)
    {

        if (convertView == null) {
            viewHolder = new ViewHolderItem();
            LayoutInflater vi = (LayoutInflater) mContext
              .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.professional_profile_list_item, null);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolderItem) convertView.getTag();
        }

   
         viewHolder.txtName = (TextView) convertView
                .findViewById(R.id.txtName);
    

      viewHolder.txtName.setText(list.getFirst_name() + " " + list.getLast_name());
     

        return convertView;
    }
   

static class ViewHolderItem {

    TextView txtName;
}
}

Retrofit2 Example Android

Just Create a Interface -

public interface RetrofitApi {
@FormUrlEncoded@POST("user_login")
Call<FXNormalLoginResponce> fixitNormalLogin(@Field("ltype") String ltype,
                                                @Field("emailid") String emailid,
                                                @Field("password") String password);
}



And create class 

import android.util.Log;
import net.technoscore.fixit.constants.AppConstants;
import net.technoscore.fixit.model.FXDeviceRegistrationResponse;
import net.technoscore.fixit.model.FXNormalLoginResponce;
import net.technoscore.fixit.model.FXProfessionalBusinessRegisterResponse;
import net.technoscore.fixit.model.FXRegistrationResponce;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitHelper {
    private static RetrofitHelper ourInstance = new RetrofitHelper();

    public static RetrofitHelper getInstance() {
        return ourInstance;
    }

    private RetrofitHelper() {
    }

    RetrofitApi retrofitapi;

    public void init() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).
                connectTimeout(5, TimeUnit.MINUTES)
                .readTimeout(5, TimeUnit.MINUTES)
                .build();


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppConstants.APP_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        retrofitapi = retrofit.create(RetrofitApi.class);
    }


public void callNormalLogin(Callback<FXNormalLoginResponce> callback, String ltype
        , String emailid, String password    ) {
    Call<FXNormalLoginResponce> response;

    Log.d("userid", "userid** " + ltype);
    Log.d("userid", "emailid** " + emailid);
    Log.d("userid", "password** " + password);

    response = retrofitapi.fixitNormalLogin(ltype, emailid, password);
    response.enqueue(callback);
}
}


Example to hit service

public class CustomerSignInActivity extends AppCompatActivity implements 
Callback<FXNormalLoginResponce> {

    RippleView button_sign_up, button_customer_sign_in;
    CustomFontTextView text_sign_up;
    EditText enter_mail, enter_password, edtemail_id, edt_password;
    RippleView rplSignIn;
    RelativeLayout rel_sign_up;
    AlertDialog dialog;
    int currentApiVersion = android.os.Build.VERSION.SDK_INT;

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


        inIt();


        // Button Clicks
        rplSignIn.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
            @Override            public void onComplete(RippleView rippleView) {
                validations();
            }
        });

        rel_sign_up.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(), 
                          CustomerSignUPActivity.class));

            }
        });
    }

    public void validations() {
        dialog.show();
        RetrofitHelper.getInstance().callNormalLogin
        (this, "1", edtemail_id.getText().toString().trim()
        , edt_password.getText().toString().trim());
    }

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

        final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE 
               | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION               
               | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN                
               | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION                
               | View.SYSTEM_UI_FLAG_FULLSCREEN                
               | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

        if (currentApiVersion >= 19) {

            getWindow().getDecorView().setSystemUiVisibility(flags);
            
            decorView.setOnSystemUiVisibilityChangeListener
              (new View.OnSystemUiVisibilityChangeListener() {

                        @Override                       
                         public void onSystemUiVisibilityChange(int visibility) {
                            if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                                decorView.setSystemUiVisibility(flags);
                            }
                        }
                    });
        }
    }


    // initialization    public void inIt() {

        edtemail_id = (EditText) findViewById(R.id.edtemail_id);
        edt_password = (EditText) findViewById(R.id.edt_password);
        dialog = new SpotsDialog(CustomerSignInActivity.this, R.style.Custom);
        rplSignIn = (RippleView) findViewById(R.id.rplSignIn);
        rel_sign_up = (RelativeLayout) findViewById(R.id.rel_sign_up);


    }

    public boolean emailValidator(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();
    }


    @Override   
 public void onResponse(Call<FXNormalLoginResponce> call, Response<FXNormalLoginResponce> 
   response) {
        dialog.dismiss();

        ArrayList<FXNormalLoginData> data = response.body().getData();
        Response_meta resmeta = response.body().getResponse_meta();
        if (Integer.parseInt(resmeta.getCode()) == 200) {

            SweetAlertDialog successDialog = new SweetAlertDialog
            (this, SweetAlertDialog.SUCCESS_TYPE);
            successDialog.getProgressHelper().setBarColor(Color.parseColor("#6CD3B5"));
            successDialog.setTitleText(resmeta.getMessage());

            successDialog.setCancelable(false);
            successDialog.show();
            successDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismissWithAnimation();
                    startActivity(new Intent(getApplicationContext(), LandingScreen.class));
                }
            });
        } else {

            FXResponseErrors[] errors = response.body().getResponse_meta().getErrors();

            final SweetAlertDialog errorDialog = new SweetAlertDialog
           (this, SweetAlertDialog.ERROR_TYPE);
            errorDialog.getProgressHelper().setBarColor(Color.parseColor("#6CD3B5"));
            errorDialog.setTitleText(resmeta.getMessage());
          if(data.size()>0)
          {
              errorDialog.setTitleText(data.get(0).getMessage());
          }
            else            if(errors.length > 0 ) {
                errorDialog.setTitleText(errors[0].getError());
            }
            else                errorDialog.setTitleText(resmeta.getMessage());
            errorDialog.setCancelable(false);
            errorDialog.show();
            errorDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener()
           {
                @Override                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismissWithAnimation();
                    errorDialog.dismiss();
                }
            });
        }


    }

    @Override    public void onFailure(Call<FXNormalLoginResponce> call, Throwable t) {
        dialog.dismiss();
    }
}


Another way to implement Retrofit2    





public class Singleton {

    Context mContext;
    private static Singleton ourInstance = new Singleton();

    public static Singleton getInstance() {
        return ourInstance;
    }

    private Singleton() {
    }

    private User mUser;

    // prolincLogin    public ApiService getApi() {

 
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor)
   .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS).build();
        Retrofit retrofit = new Retrofit.Builder()
                //  .baseUrl("http://prolinc.in/prolincApi/")                
         .baseUrl("http://prolinc.in/prolinc_dev/prolincApi/")
                .client(client)
                        //.baseUrl("http://192.168.1.87/prolinc/prolincApi/") 
.addConverterFactory(GsonConverterFactory.create())
               /* .addConverterFactory(GsonConverterFactory.create(gson))*/               
 .build();


        return retrofit.create(ApiService.class);

    }


}



Example to hit service

public void sendOTP() {
    SharedPrefHelper sph = new SharedPrefHelper(this);
    Gson gsn = new Gson();
    String js = sph.getString("USERDATA", "");
    UserData objUserData = gsn.fromJson(js, UserData.class);
    String token = objUserData.getToken();
    String UserID = objUserData.getUserId();
    String phone = objUserData.getPhone();
    mApiService = Singleton.getInstance().getApi();
    mApiService.sedOTP(UserID, phone).enqueue
 (new Callback<AbstractResponseList<ResponseMeta, OTPModel>>() {
        @Override       
 public void onResponse(Response<AbstractResponseList<ResponseMeta, OTPModel>> response) {

            ResponseMeta responseMeta = response.body().getResponseMeta();
            List<OTPModel> data = response.body().getData();
            if (responseMeta.getCode() == 200) {
                Toast.makeText(OTPVerificationActivity.this
            data.get(0).getMessage(), Toast.LENGTH_SHORT).show();

            } else {

            }
        }

        @Override        
      public void onFailure(Throwable t) {
    Toast.makeText(OTPVerificationActivity.this, "Try again!", Toast.LENGTH_SHORT).show();
        }
    });
}