Pages

Monday, 11 December 2017

    How to Call Simple  POST method API

Objective :-
                  
               The main objective of this post is to help you understand how to call simple post method  API  in your android Application.


You will get Final Output :-
   









  • First implement below Dependencies in app:Build.gradle

  • compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    compile 'com.squareup.okhttp:okhttp:2.4.0'







    • In This activity you need  2 XML files.


      • activity_view_productname.xml:-
      <layout xmlns:card_view="http://schemas.android.com/apk/res-auto"
          xmlns:android="http://schemas.android.com/apk/res/android">
      
          <LinearLayout
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">
      
      
              <android.support.v7.widget.CardView
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:layout_margin="8dp"
                  card_view:cardCornerRadius="10dp">
      
                  <LinearLayout
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:gravity="center"
                      android:orientation="vertical">
      
      
                      <android.support.v7.widget.RecyclerView
      
                          android:id="@+id/rvCategoryList"
                          android:layout_width="match_parent"
                          android:layout_height="wrap_content"
                          android:layout_gravity="center"
                          android:layout_marginTop="10dp">
      
                      </android.support.v7.widget.RecyclerView>
                  </LinearLayout>
      
              </android.support.v7.widget.CardView>
          </LinearLayout>
      </layout>
      
      
      • view_product_name.xml:-
      <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="@dimen/_10sdp" android:visibility="visible"> <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="@dimen/_4sdp" android:layout_gravity="center"> <TextView android:id="@+id/txtCategoryName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:ellipsize="end" android:lines="3" android:maxLines="3" android:text="medicine name" android:textColor="@color/colorGray" android:textSize="@dimen/_15sdp" android:textStyle="bold" /> </android.support.v7.widget.CardView> </LinearLayout> </layout>
      • In this program use the POST Request method API.
      • First declare API in ApiEndpointInterface interface Class
      • ApiEndpointInterface:-
      
      public interface ApiEndpointInterface {
      
          @Multipart    @POST("Welcome/dashboard")
          Call<ArrayList<ProductNameInfo>> ProductData(@Part("key") RequestBody key);
      }
      
      
      • In this Api Classs you can use OkHttps Credentials is "Key".
      • User was get data for above OkHttps Credentials.
      • Multipart requests are used when @Multipart is present on the method. Parts are declared using the @Part annotation.
      • Multipart parts use one of Retrofit's converters or they can implement RequestBody to handle their own serialization.
      • After make a Retrofit Builder Class.
      • RetrofitBuilder.java:-
      
      public class RetrofitBuilder {
          public static final String BASE_URL = "http://www.erestaurantapp.com/EmedDictionary/index.php/";
      
          public  static final RetrofitBuilder retrofitBuilder=new RetrofitBuilder();
          private RetrofitBuilder(){
      
          }
          public static RetrofitBuilder getInstance() {
              return retrofitBuilder;
          }
      
          public ApiEndpointInterface getRetrofit(final Context context) {
      
              final OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
      
              final Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ItemTypeAdapterFactory())
                      .setLenient().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
      
      
      
              final Retrofit retrofit = new Retrofit.Builder()
                      .baseUrl(BASE_URL)
                      .client(httpClient.build())
                      .addConverterFactory(GsonConverterFactory.create(gson))
                      .build();
      
              return retrofit.create(ApiEndpointInterface.class);
          }
      
      
      }
      
      
      • In the Retrofit Builder class i have add the BASE_URL.
      • Retrofit.Builder class - Instance which uses the interface
      and the Builder API which allows defining the URL end point for
           the HTTP operation.
      • If you need to communicate with an API that uses a content-format
      that Retrofit does not support out of the box (e.g. YAML, txt, custom format)
           or you wish to use a different library to implement an existing format, you can
          easily create your own converter. Create a class that extends the Converter.Factor           and pass in an instance when building your adapter.
      • ItemTypeAdapterFactory:-
      class ItemTypeAdapterFactory implements TypeAdapterFactory {
          private static final String KEY_STATUS = "status";
          private static final String KEY_MESSAGE = "msg";
          private static final String KEY_RESULT = "result";
      
      
          @Override    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
              final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
              final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
      
              return new TypeAdapter<T>() {
      
                  public void write(JsonWriter out, T value) throws IOException {
                      delegate.write(out, value);
                  }
      
                  public T read(JsonReader in) throws IOException {
      
                      JsonElement jsonElement = elementAdapter.read(in);
                      if (jsonElement.isJsonObject()) {
      
                          final JsonObject jsonObject = jsonElement.getAsJsonObject();
      
                          String status = "";
                          String message = "";
                          if (jsonObject.has(KEY_STATUS) && jsonObject.has(KEY_MESSAGE)) {
                              status = jsonObject.get(KEY_STATUS).getAsString();
                              if (!jsonObject.get(KEY_MESSAGE).isJsonNull())
                                  message = jsonObject.get(KEY_MESSAGE).getAsString();
      
                              if (status.equalsIgnoreCase("success")) {
                                  if (jsonObject.get(KEY_RESULT).isJsonObject()) {
                                      jsonElement = jsonObject.get(KEY_RESULT).getAsJsonObject();
                                  } else if (jsonObject.get(KEY_RESULT).isJsonArray()) {
                                      jsonElement = jsonObject.get(KEY_RESULT).getAsJsonArray();
                                  }
                              } else {
                                  throw new IOException(message);
                              }
                          }
      
                      }
      
                      return delegate.fromJsonTree(jsonElement);
                  }
              }.nullSafe();
          }
      }
      
      
      • The ItemTypeAdapterFactory use the Responce Result was display in Your OWN Formet.
      • The above class is my own class.
      • I have use my Selected formet.
      • The Response was display in my selected Formet.
      • Example of my formet responce :-
      "status": "1", "msg": "Category data found Successfull", "result": [ { "category_id": "4", "category_name": "Alternative medicine", "photo": "http://apnadawabazar.com/admin_anytimehealthcare/data/category/main/cat_alternative_medicine.png" }, { "category_id": "2", "category_name": "Carers", "photo": "http://apnadawabazar.com/admin_anytimehealthcare/data/category/main/cat_carers.png" }, { "category_id": "18", "category_name": "child care", "photo": "http://apnadawabazar.com/admin_anytimehealthcare/data/category/main/cat_optition.png" }
      
      
      • After i have use my main activity.
      •  ViewProductNameActivity:-
       private ActivityViewProductnameBinding binding;
          public ProductNameListAdapter adapter;
          private Context mContext;
          private ArrayList<ProductNameInfo> mProductNameInfos = new ArrayList<>();
      
          @Override    
               protected void onCreate(@Nullable Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              mContext = this;
              binding = DataBindingUtil.setContentView(this, R.layout.activity_view_productname);
      
      
            RVLayoutManager.setVerticalLayoutManager(mContext,binding.rvCategoryList);
              adapter = new ProductNameListAdapter(mContext,  mProductNameInfos);
              binding.rvCategoryList.setAdapter(adapter);
              requestToGetProductCategoryList();
      
          }
      
          private void requestToGetProductCategoryList() {
              RequestBody key = RequestBody.create(MediaType.parse("text/plain"), "gguhy");
              Call<ArrayList<ProductNameInfo>> arrayListCall = RetrofitBuilder.getInstance().getRetrofit(mContext)
                      .ProductData(key);
      
              arrayListCall.enqueue(new RetrofitCallback<ArrayList<ProductNameInfo>>(mContext) {
                  @Override            
                      public void onSuccess(ArrayList<ProductNameInfo> models) {
      
                      mProductNameInfos = models;
                      if ( mProductNameInfos != null &&  mProductNameInfos.size() > 0) {
                          binding.rvCategoryList.setAdapter(new ProductNameListAdapter(mContext,  mProductNameInfos));
                      }
                  }
      
                  @Override            
                      public void onFail(String message) {
                      Log.e("@@@3@@@","Not Response......");
                  }
              });
          }
      }
      
      
      • In above class i have use LinearLayout.
      • But,i have use my layout class..RVLayoutManager.
      • RVLayoutManager:-
      class RVLayoutManager {
          public static void setGridLayoutManager(Context context, RecyclerView recyclerView, int count) {
              recyclerView.setLayoutManager(new GridLayoutManager(context, count));
          }
      
          public static void setVerticalLayoutManager(Context context, RecyclerView recyclerView) {
              LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
              recyclerView.setLayoutManager(linearLayoutManager);
          }
      
          public static void setHorizaontaLayoutManager(Context context, RecyclerView recyclerView) {
              LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
              recyclerView.setLayoutManager(linearLayoutManager);
          }
      }
       
      • In The RVLayoutManager Class i have use multiple method of layout.
      • so i have use any other class .
      • The above activity i have use the Retrofit Callback class.
      • RetrofitCallback:-
      public abstract class RetrofitCallback<T> implements Callback<T> {
          private Context context;
      
          public RetrofitCallback(Context c) {
              context = c;
          }
      
          public abstract void onSuccess(T arg0);
      
          public abstract void onFail(String message);
      
          @Override    public void onResponse(Call<T> call, Response<T> response) {
              if (response.isSuccessful() && response.code() == 200) {
                  onSuccess(response.body());
              } else {
                  Log.e("@@@1@@@","Success.....");
              }
          }
      
          @Override    public void onFailure(Call<T> call, Throwable error) {
      
              Log.e("@@@2@@@","fail.....");
          }
      }
      • Callback methods are executed using the Retrofit callback executor
      • onFailure(Call<T> call, Throwable t)
        Invoked when a network exception occurred talking to the server or when an unexpected exception occurred creating the request or processing the response.
      • onResponse(Call<T> call, Response<T> respons)
        Invoked for a received HTTP response.
      • ProductNameListAdapter:-
      class ProductNameListAdapter extends RecyclerView.Adapter<ProductNameListAdapter.MyViewHolder>{
      
          private Context mContext;
          private ArrayList<ProductNameInfo> mProductName;
      
      
          public ProductNameListAdapter(Context context, ArrayList<ProductNameInfo> productNames) {
              mContext = context;
              mProductName = productNames;
          }
      
      
      
          @Override    public ProductNameListAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int type) {
              ViewProductNameBinding viewProductNameBinding = ViewProductNameBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
              return new MyViewHolder(viewProductNameBinding);
      
          }
      
          @Override    public void onBindViewHolder(MyViewHolder holder, final int position) {
              final ProductNameInfo productCategoryInfo = mProductName.get(position);
      
              holder.binding.txtCategoryName.setText(mProductName.get(position).getCategoryName());
      
          }
      
          @Override    public int getItemCount() {
              return mProductName.size();
      
          }
      
      
      
          public static class MyViewHolder extends RecyclerView.ViewHolder {
              private final ViewProductNameBinding binding;
      
              public MyViewHolder(ViewProductNameBinding binding) {
                  super(binding.getRoot());
                  this.binding = binding;
              }
          }
      }
      
      
      • ProductNameInfo:-
      public class ProductNameInfo {
      
      
          @SerializedName("category_name")
          @Expose    private String categoryName;
      
          public String getCategoryName() {
              return categoryName;
          }
      }
      
      
      
      
      • The ProductNameInfo class is POJO class;
      • In this case, the JSON key category_name is mapped to the class field category_name. But note that since they are the same, there is no need to include the @SerializedName annotation on the field because Gson will map it automatically for us.
      • The @Expose annotation indicates that the class member should be exposed for JSON serialization or deserialization. 

           How to Call Simple  POST method API Objective :-                                     The main objective of this post is to hel...