Skip to main content

Android API Calling Using OkHTTP And Dao

1 ) Create Web Field Class


public class Webfields
{

    public static final String API_TEST_API = "TESTAPI";
    public static final int intFlagShow = 1;
    public static final String BASE_URL= "http://pratikbutani.x10.mx/";

    public final static  class TESTAPI
    {
        public final static String MODE = "json_data.json";
        public final static String RESPONSE_ARR_MAIN_CHILD_TAG = "contacts";
        public final static String RESPONSE_USER_ID = "id";
        public final static String RESPONSE_NAME = "name";
        public final static String RESPONSE_EMAIL = "email";
        public final static String RESPONSE_ADDRESS = "address";
        public final static String RESPONSE_GENDER = "gender";
        public final static String RESPONSE_PROFILE_PIC= "profile_pic";
        public final static String RESPONSE_PHONE= "phone";
        public final static String RESPONSE_MOBILE= "mobile";
        public final static String RESPONSE_HOME= "home";
        public final static String RESPONSE_OFFICE= "office";
    }


2 ) Create Model Class
public class ContactsModel
{
    String id, name, email, address, gender, home, mobile, office;
    ArrayList<PhoneModel> phoneModelArrayList;

    public ContactsModel( String id,String name,String email, String address,String gender,String home,
                          String mobile, String office)
    {
        this.id=id;
        this.name=name;
        this.email=email;
        this.address=address;
        this.gender=gender;
        this.home=home;
        this.mobile=mobile;
        this.office=office;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getOffice() {
        return office;
    }

    public void setOffice(String office) {
        this.office = office;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getHome() {
        return home;
    }

    public void setHome(String home) {
        this.home = home;
    }

    public ArrayList<PhoneModel> getPhoneModelArrayList() {
        return phoneModelArrayList;
    }

    public void setPhoneModelArrayList(ArrayList<PhoneModel> phoneModelArrayList) {
        this.phoneModelArrayList = phoneModelArrayList;
    }
}
3 ) Create Dao Class
public class TestAPIDao implements OnAPItestListener
{
    private String id;
    private String name;
    private String email;
    private String address;
    private String gender;
    private String mobile;
    private String home;
    private String office;
    private Context mActivity;
    private String phone;

    public TestAPIDao(Context context)

    {
        this.mActivity=context;
    }
    @Override    
    public ArrayList<ContactsModel> getContacts(Context context, JSONObject jsonObject)
    {
        ArrayList<ContactsModel> mArrFileVersionHistory = new ArrayList<ContactsModel>();
        try        {
            JSONArray jsonArray = jsonObject.getJSONArray(Webfields.TESTAPI.RESPONSE_ARR_MAIN_CHILD_TAG);
            for(int i=0; i<jsonArray.length(); i++)
            {
                JSONObject jsonFileList = jsonArray.getJSONObject(i);

                id = jsonFileList.getString(Webfields.TESTAPI.RESPONSE_USER_ID);
                name = jsonFileList.getString(Webfields.TESTAPI.RESPONSE_NAME);
                email = jsonFileList.getString(Webfields.TESTAPI.RESPONSE_EMAIL);
                address = jsonFileList.getString(Webfields.TESTAPI.RESPONSE_ADDRESS);
                gender = jsonFileList.getString(Webfields.TESTAPI.RESPONSE_GENDER);
                phone=jsonFileList.getString(Webfields.TESTAPI.RESPONSE_PHONE);
                JSONObject jsonObject1=new JSONObject(phone);

                for(int j=0;j<jsonObject1.length();j++)
                {
                    mobile = jsonObject1.getString(Webfields.TESTAPI.RESPONSE_MOBILE);
                    home = jsonObject1.getString(Webfields.TESTAPI.RESPONSE_HOME);
                    office= jsonObject1.getString(Webfields.TESTAPI.RESPONSE_OFFICE);
                }

                ContactsModel contactsModel  = new ContactsModel(id,name,email,address,gender,mobile,home,office);
                mArrFileVersionHistory.add(contactsModel);
            }

        } catch (Exception exception)
        {
            Toast.makeText(context, "Error" + exception, Toast.LENGTH_SHORT).show();
        }
        return mArrFileVersionHistory;
    }

}

4 ) Create Dao Interface Class
public interface OnAPItestListener 
{
   ArrayList<ContactsModel> getContacts(Context context, JSONObject jsonObject);
}


5 ) Create OkHTTP Class
 
public class OkHTTPtestAPI extends AsyncTask<String, JSONObject, JSONObject> {

    private String strRefId;
    private Activity context;
    private String strAPIName;
    private String strAPI,mId;
    private AlertDialog dialog;
    private int intDialogShow = 0;
    private ProgressDialog progressDialog;
    private OnAPItestListenerOkHTTP onAPItestListener;

    public OkHTTPtestAPI(Activity context, String strAPI, String strAPIName,
                                                         int intDialogShow, OnAPItestListenerOkHTTP onAPItestListener) {
        this.onAPItestListener = onAPItestListener;
        this.strAPI = strAPI;
        this.intDialogShow = intDialogShow;
        this.strAPIName = strAPIName;
        this.context = context;
    }

        @Override    
        protected void onPreExecute() {
        if (intDialogShow == 1) {
            progressDialog = new ProgressDialog(context);
            progressDialog.setCancelable(false);
            progressDialog.setMessage("Please Wait...");
            progressDialog.setTitle("");
            progressDialog.show();
//          dialog = new SpotsDialog(context, R.style.ProgressDialog);//            
            dialog.show();        
        }
        super.onPreExecute();
    }

    @Override    
    protected JSONObject doInBackground(String... param) {
        try {
            if (strAPI.equalsIgnoreCase(Webfields.API_TEST_API))
            {
                strAPIName = "json_data.json";
            }


            AndroidNetworking.get(Webfields.BASE_URL + strAPIName)
                    .setPriority(Priority.HIGH)
                    .build()
                    .getAsJSONObject(new JSONObjectRequestListener()
                    {

                        @Override                        
                        public void onResponse(JSONObject jsonResult)
                        {
                            try                            {
                                if (strAPI.equalsIgnoreCase(Webfields.API_TEST_API))
                                {
                                    if (jsonResult != null)
                                    {
                                        onAPItestListener.onUpdateComplete(jsonResult, true);
                                    }
                                    else                                    {
                                        onAPItestListener.onUpdateComplete(jsonResult, false);
                                    }
                                }
                            } catch (Exception exception)
                            {

                            }
                            finally                            {
                                if (intDialogShow == 1)
                                {
                                    progressDialog.dismiss();
                                }
                            }
                        }

                        @Override                        
                        public void onError(ANError anError)
                        {
                            try                            {
                                if (intDialogShow == 1)
                                {
                                    progressDialog.dismiss();
                                }
//                                AlertDialogUtility.SHOW_TOAST(context, anError.getErrorBody());                            }
                            catch (Exception exception)
                            {
                            }
                        }
                    });

        } catch (Exception exception) {
        }
        return null;
    }

    @Override    
    protected void onPostExecute(JSONObject jsonResult) {
        super.onPostExecute(jsonResult);
    }
}


6 ) Create OkHTTP Interface Class
    public interface OnAPItestListenerOkHTTP 
    {

        void onUpdateComplete(JSONObject jsonObject, boolean isSuccess);
    }


7 ) OkHTTP API Call
  
new OkHTTPtestAPI(mActivity, Webfields.API_TEST_API,
        Webfields.TESTAPI.MODE, Webfields.intFlagShow,
        new OnAPItestListenerOkHTTP()
        {
            @Override            
            public void onUpdateComplete(JSONObject jsonObject, boolean isSuccess)
            {
                if (isSuccess)
                {
                    TestAPIDao testAPIDao = new TestAPIDao(mActivity);
                    contactsModels = testAPIDao.getContacts(mActivity, jsonObject);
                    recyclerView.setHasFixedSize(true);
                    LinearLayoutManager linearLayoutManager;
                    linearLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
                    contactAdapter = new ContactAdapter(mActivity, contactsModels);
                    recyclerView.setLayoutManager(linearLayoutManager);
                    recyclerView.setAdapter(contactAdapter);
                    Toast.makeText(mActivity, "", Toast.LENGTH_SHORT).show();
                }
            }
        }).execute();   

---------------------------------------------------------------------------

Note : 
1 ) Manifest Permission
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 
2 )Require Build Gradle 


compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support:design:26.+'
compile 'com.android.support:support-v4:26.+'
compile 'com.android.support:recyclerview-v7:26.+'
compile 'com.amitshekhar.android:android-networking:0.3.0'

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