Retrofit android Example with Recyclerview

How to use api in android app| how to integrate api in android using retrofit

dependency for retrofit

   implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

Step 1:- Create a Package name Api make a class

ApiClient.java

package com.example.firebasedatabase.Api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public  static Retrofit RETROFIT = null;
    public static final  String API_BASE_URL ="https://happylife.guru/";

     public  static  Retrofit getClient(){

         if (RETROFIT ==null){

             OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
             Gson gson = new GsonBuilder().create();

             RETROFIT = new Retrofit.Builder()
                     .baseUrl(API_BASE_URL)
                     .client(okHttpClient)
                     .addConverterFactory(GsonConverterFactory.create(gson)).build();


         } return  RETROFIT;

     }


}

Step2:- Api Interface

ApiInterface.java

package com.example.firebasedatabase.Api;


import com.example.firebasedatabase.models.Food_Responce;

import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {

    @GET("/getpoetry.php")
    Call<Food_Responce> fetchfooddata();



}

Step3:- Fragment_booking.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragments.Booking_Fragment">


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/reconline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Step4:- layout for recyclerview item

food_single_item.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="4dp"
        android:gravity="center"
        android:orientation="vertical"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/foodname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:padding="13dp"
             />

        <TextView
            android:id="@+id/foodtitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:singleLine="false"
            android:text="Hardwahfduegfheghufehvfehbvfhebvre"
            android:textColor="@color/black"
            android:textSize="10dp" />

        <View
            android:layout_marginTop="10dp"
            android:layout_width="match_parent"
            android:background="@color/black"
            android:layout_height="1dp"/>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Step5:- FoodAdapter.java

package com.example.firebasedatabase.Adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.firebasedatabase.R;
import com.example.firebasedatabase.models.FoodModel;

import java.util.List;

public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.holder> {

    Context context;
    List<FoodModel> foodModels;

    public FoodAdapter(Context context, List<FoodModel> foodModels) {
        this.context = context;
        this.foodModels = foodModels;
    }

    @NonNull
    @Override
    public FoodAdapter.holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.food_single_item,parent,false);

         return  new holder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull FoodAdapter.holder holder, int position) {
        FoodModel model = foodModels.get(position);
         holder.foodtitle.setText(model.getPoet_name());
         holder.foodname.setText(model.getPoetry_data());

    }

    @Override
    public int getItemCount() {
        return foodModels.size();
    }

    public class holder extends  RecyclerView.ViewHolder {
        TextView  foodname,foodtitle;
        public holder(@NonNull View itemView) {
            super(itemView);
            foodname = itemView.findViewById(R.id.foodname);
            foodtitle = itemView.findViewById(R.id.foodtitle);

        }
    }
}

Step6:- Booking_Fragment.java

package com.example.firebasedatabase.Fragments;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.firebasedatabase.Adapters.FoodAdapter;
import com.example.firebasedatabase.Api.ApiInterface;
import com.example.firebasedatabase.R;
import com.example.firebasedatabase.Utils.Utilmethods;
import com.example.firebasedatabase.databinding.FragmentBookingBinding;
import com.example.firebasedatabase.models.FoodModel;
import com.example.firebasedatabase.models.Food_Responce;

import java.util.List;

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

public class Booking_Fragment extends Fragment {

    FragmentBookingBinding binding;
    ApiInterface apiInterface;
    ProgressDialog progressDialog;
    FoodAdapter foodAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
         binding= FragmentBookingBinding.inflate(inflater,container,false);
        Retrofit retrofit = com.example.firebasedatabase.Api.ApiClient.getClient();
        apiInterface = retrofit.create(com.example.firebasedatabase.Api.ApiInterface.class);
        progressDialog = new ProgressDialog(getActivity());
        getfooddata();
        return binding.getRoot();
    }

    private void setadapter(List<FoodModel> foodModels) {
        foodAdapter = new FoodAdapter(getActivity(), foodModels);


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        binding.reconline.setLayoutManager(linearLayoutManager);
        binding.reconline.setAdapter(foodAdapter);


    }



    public void getfooddata() {
        Utilmethods.showDialog(progressDialog);
        Log.d("hit","hit" );

        apiInterface.fetchfooddata().enqueue(new Callback<Food_Responce>() {
            @Override
            public void onResponse(Call<Food_Responce> call, Response<Food_Responce> response) {


                Log.d("hitres","hitonrea");

                try {
                    if (response != null) {

                        Log.e("apihitcho","api responce: "+ response.body().getStatus());


                        if (response.body().getStatus().equals("1")) {
                            setadapter(response.body().getData());
                            Utilmethods.exitDialog(progressDialog);
//                            setadapterhardware(response.body().getData());

                        } else {

//                            Toast.makeText(OrderActivity.this, response.body().getStatus(), Toast.LENGTH_SHORT).show();
                        }

                    }

                } catch (Exception e) {
                    Log.e("exp", e.getLocalizedMessage());
                }
            }

            @Override
            public void onFailure(Call<Food_Responce> call, Throwable t) {
                Log.e("failure", t.getLocalizedMessage());
                Log.d("hitresfail","hitonrea  " + t.getMessage());
            }
        });

//
    }


}

Step7:- Create Util folder and create a java class for Utility method .

Utilmethods.java:-

package com.example.firebasedatabase.Utils;

import android.app.ProgressDialog;
import android.content.Context;

public class Utilmethods {

    Context context;

    public static void showDialog(ProgressDialog progressDialog) {
        progressDialog.setMessage("Please Wait....");
        progressDialog.setCancelable(true);
        progressDialog.show();
    }
    public static void exitDialog(ProgressDialog progressDialog) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }


}