Skip to main content

API Post OkHTTP

1 ) Main Activity

callLoginAPI(strUsername, strPassword);
  private void callLoginAPI(final String strUsername, final String strPassword) {
        try {
            if (ConnectivityDetector.IS_INTERNET_AVAILABLE(mActivity))
            {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(WebFields.LOGIN.REQUEST_USERNAME, strUsername);
                jsonObject.put(WebFields.LOGIN.REQUEST_PASS, strPassword);
                jsonObject.put(WebFields.LOGIN.REQUEST_BROWSER, strBrowser);
                jsonObject.put(WebFields.LOGIN.REQUEST_OS, strOS);
                jsonObject.put(WebFields.LOGIN.REQUEST_DEVICE, strDevice);
                jsonObject.put(WebFields.LOGIN.REQUEST_APPLICATION_ID, Integer.parseInt("3"));
                jsonObject.put(WebFields.LOGIN.REQUEST_USERTYPE, Integer.parseInt("1"));
                jsonObject.put(WebFields.LOGIN.REQUEST_STAY_SIGN_IN,Boolean.parseBoolean("true"));

                new OkHTTPCallBackPostLogin(mActivity, AppConstants.API_LOGIN,
                        jsonObject, WebFields.LOGIN.MODE, AppConstants.intFlagShow,
                        new OnUpdateListenerJsonObject() {
                            @Override                            public void onUpdateComplete(JSONObject jsonObject, boolean isSuccess) {
                                if (isSuccess)
                                {
                                    try                                    {
                                        String mToken = jsonObject.getString(WebFields.LOGIN.RESPONSE_TOKEN);
                                        String mUserId=jsonObject.getString(WebFields.LOGIN.RESPONSE_USER_ID);
                                        String mclientId=jsonObject.getString(WebFields.LOGIN.RESPONSE_CLENT_ID);
                                        JSONObject mPermissions = jsonObject.getJSONObject(WebFields.LOGIN.RESPONSE_PERMISSIONS);
//                                        String mIsAdmin = mPermissions.getString(WebFields.LOGIN.RESPONSE_All);                                        Common.insertLog("IsAdmin"+mIsAdmin);
                                        mKeyIsLogin = AppConstants.STR_BOOL_TRUE;
                                        sessionManager.saveLoginDetails(mActivity, mToken, strUsername, strPassword, mKeyIsLogin);
                                        sessionManager.setIsLogin(mActivity, mKeyIsLogin);
                                        sessionManager.setToken(mActivity, mToken);
//                                        sessionManager.setClientId(mActivity, mclientId);                                        sessionManager.setUserId(mActivity, mUserId);
                                        sessionManager.setUserEmail(mActivity,strUsername);
                                        callPermissionAPI(mToken,mUserId,mclientId);
                                    } catch (JSONException exception)
                                    {
                                        Common.exceptionPrintStackTrace(mActivity, AppConstants.STR_EXCEPTION, exception);
                                    }
                                }
                            }
                        }).execute();
            }
            else            {
                SnackBarAlertDialog.ERROR(mActivity, AppConstants.STR_INETRNET_ALERT_MESSAGE);
            }
        } catch (Exception exception)
        {
            Common.exceptionPrintStackTrace(mActivity, AppConstants.STR_EXCEPTION, exception);
        }
    }


2 ) OkHTTP Class
import android.app.Activity;
import android.os.AsyncTask;
import android.view.View;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.leo.simplearcloader.SimpleArcDialog;
import com.ondiscus.greenbox.AppUtils.AppConstants;
import com.ondiscus.greenbox.AppUtils.Common;
import com.ondiscus.greenbox.AppUtils.ConnectivityDetector;
import com.ondiscus.greenbox.AppUtils.ProgressBarCustom;
import com.ondiscus.greenbox.AppUtils.SessionManager;
import com.ondiscus.greenbox.AppUtils.SnackBarAlertDialog;
import org.json.JSONObject;
public class OkHTTPCallBackPostLogin extends AsyncTask<String, JSONObject, JSONObject>
{
    private View mView;
    private String strId;
    private String strAPI;
    private String strAPIName;
    private Activity mActivity;
    private JSONObject jsonObject;
    private int intDialogShow = 0;
    private SimpleArcDialog mDialog;
    private OnUpdateListenerJsonObject onUpdateListenerJsonObject;
    public OkHTTPCallBackPostLogin(Activity mActivity, String strAPI, JSONObject jsonObject, String strAPIName,
                                   int intDialogShow, OnUpdateListenerJsonObject onUpdateListenerJsonObject) {
        this.onUpdateListenerJsonObject = onUpdateListenerJsonObject;
        this.strAPI = strAPI;
        this.jsonObject = jsonObject;
        this.intDialogShow = intDialogShow;
        this.strAPIName = strAPIName;
        this.mActivity = mActivity;
        mDialog = new SimpleArcDialog(mActivity);
    }
    @Override
    protected void onPreExecute()
    {
        if (!ConnectivityDetector.IS_INTERNET_AVAILABLE(mActivity))
        {
            SnackBarAlertDialog.ERROR(mActivity, AppConstants.STR_INETRNET_ALERT_MESSAGE);
            return;
        }
        else if (strAPI.equalsIgnoreCase(AppConstants.API_LOGOUT))
        {
            strId= SessionManager.getUserId(mActivity);
            strAPIName = WebFields.LOGOUT.MODE;
        }
        if (intDialogShow == 1)
        {
           
        mDialog= new SimpleArcDialog(mActivity);
        ProgressBarCustom.startProgressBar(mActivity,mDialog);
        }
        super.onPreExecute();
    }
    @Override
    protected JSONObject doInBackground(String... param)
    {
        try {
            if (strAPI.equalsIgnoreCase(AppConstants.API_LOGIN))
            {
                strAPIName = WebFields.LOGIN.MODE;
            }
            Common.insertLog("API NAME :: " + strAPIName);
            AndroidNetworking.post(WebFields.BASE_URL_LOGIN + strAPIName)
                    .addHeaders(AppConstants.CONTENT_TYPE, "application/json")
                    .addJSONObjectBody(jsonObject)
                    .setPriority(Priority.HIGH)
                    .build()
                    .getAsJSONObject(new JSONObjectRequestListener()
                    {
                        @Override
                        public void onResponse(JSONObject jsonResult)
                        {
                            try
                            {
                                Common.insertLog("response login :: " + jsonResult);
                                if (jsonResult != null)
                                {
                                     if(jsonResult.getString(WebFields.LOGIN.RESPONSE_STATUS).equals("401"))
                                        {
                                            onUpdateListenerJsonObject.onUpdateComplete(jsonResult, false);
                                            SnackBarAlertDialog.ERROR(mActivity, AppConstants.STR_VALID_USER_NAME);
                                        }
                                        else if (jsonResult.getString(WebFields.LOGIN.REQUEST_TOKEN).equalsIgnoreCase(""))
                                        {
                                            onUpdateListenerJsonObject.onUpdateComplete(jsonResult, false);
                                            SnackBarAlertDialog.ERROR(mActivity, AppConstants.ALERT_ERROR);
                                        }
                                        else
                                        {
                                         onUpdateListenerJsonObject.onUpdateComplete(jsonResult, true);
                                         SnackBarAlertDialog.SUCCESS(mActivity, AppConstants.STR_LOGGED_IN);
                                        }
                                } else
                                {
                                    SnackBarAlertDialog.ALERT(mActivity, AppConstants.STR_NO_RESPONSE);
                                }
                            } catch (Exception exception)
                            {
                                Common.exceptionPrintStackTrace(mActivity, AppConstants.STR_EXCEPTION, exception);
                            } finally
                            {
                                if (intDialogShow == 1)
                                {
                                    ProgressBarCustom.stopProgressBar(mDialog);
                                }
                            }
                        }
                        @Override
                        public void onError(ANError anError)
                        {
                            try
                            {
                                if (intDialogShow == 1)
                                {
                                    ProgressBarCustom.stopProgressBar(mDialog);
                                }
            SnackBarAlertDialog.ALERT(mActivity, AppConstants.STR_NO_RESPONSE);
                                Common.insertLog("ERROR 1" + anError.getErrorBody());
                                Common.insertLog("ERROR 2" + anError.getErrorDetail());
                                Common.insertLog("ERROR 3" + anError.getErrorCode());
                                Common.insertLog("ERROR 4" + anError.getResponse());
                            } catch (Exception exception)
                            {
                                Common.exceptionPrintStackTrace(mActivity, AppConstants.STR_EXCEPTION, exception);
                            }
                        }
                    });
        } catch (Exception exception)
        {
            Common.exceptionPrintStackTrace(mActivity, AppConstants.STR_EXCEPTION, exception);
        }
        return null;
    }
    @Override
    protected void onPostExecute(JSONObject jsonResult)
    {
        super.onPostExecute(jsonResult);
    }
}


3 ) Listener Class
public interface OnUpdateListenerJsonObject {

    void onUpdateComplete(JSONObject jsonObject, boolean isSuccess);
}


Notes: 

1 ) Build Graddle

compile 'com.android.support:design:27.1.1'compile 'com.android.support:support-v4:27.1.1'
compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.amitshekhar.android:android-networking:1.0.1'

2 ) Manifest Permission

<uses-permission android:name="android.permission.INTERNET"/>





Comments

Popular posts from this blog

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 ) .meth...

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...