Skip to main content

API Retrofit Android Example With Recyclerview || How to fetch data from Api to Android Recycler View

How To Fetch API (JSON) Data to Android RecylcerView





 "I have used FREE TEST API you can also use for practice"

            1. Goto:    https://jsonplaceholder.typicode.com/ 

            2. Scroll down your find the ROUTS Section 

            3. Click on GET /POST

            Here you can find the URL which will use in our project. You can use your own URL also.

                            

                       
Best WordPress Hosting


Steps To Fetch API Through Retrofit

1. Add permission in the manifest:

<uses-permission android:name="android.permission.INTERNET" />
2. Add Libreries in the Gradle:
implementation 'com.google.code.gson:gson:2.8.7'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
3. Create Model Class:
    Model class variable names should be same as it is in json variables.

           "id, title, body, json api Variables  (we will accsess these data"

        public class model {
int id;
String title;
String body;

public model(int id, String title, String body) {
this.id = id;
this.title = title;
this.body = body;

}

public int getId() {
return id;
}

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

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getBody() {
return body;
}

public void setBody(String body) {
this.body = body;
}
}

 



4. Create Api Interface:
              
            copy post from link past in @GET("post")  
public interface Api {

@GET("posts")
Call<List<model>> getdata();
}



5. Create Controller Class:
private static final String url ="https://jsonplaceholder.typicode.com/";
private static Controler clientControler;
private static Retrofit retrofit;

Controler(){
retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}

public static synchronized Controler getInstance(){
if(clientControler==null){
clientControler =new Controler();
}

return clientControler;
}

Api getapi(){
return retrofit.create(Api.class);
}


}
6. Create Layout View  for RecycerView:

  • Right Click on resource 
  • Create new Layout past code
       <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="@color/white">

<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@color/white"
android:layout_margin="10dp"
app:cardCornerRadius="10dp"
app:cardElevation="8dp"
>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ID:"
android:textSize="30dp"
android:textColor="@color/black"
android:textStyle="bold"></TextView>

<TextView
android:id="@+id/id"
android:hint="ID"
android:textSize="20dp"
android:textColor="@color/black"

android:layout_width="match_parent"
android:layout_height="wrap_content"></TextView>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TITLE:"
android:textSize="30dp"
android:textColor="@color/black"
android:textStyle="bold"></TextView>
<TextView
android:id="@+id/title"
android:hint="TITLE"
android:textColor="@color/black"
android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"></TextView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BODY:"
android:textSize="30dp"
android:textColor="@color/black"
android:textStyle="bold"></TextView>
<TextView
android:id="@+id/body"
android:hint="BODY"
android:textColor="@color/black"

android:textSize="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>


</RelativeLayout>
 


7. Create Recycler View in Main Activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">


<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
android:layout_height="wrap_content" />


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

</androidx.recyclerview.widget.RecyclerView>
</RelativeLayou>



8. Create Adapter Class To SetData into Recylcer Layout 

public class RecAdapter extends RecyclerView.Adapter<RecAdapter.MyViewHolder> {

List<model> data;

public RecAdapter(List<model> data) {
this.data = data;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view,parent,false);

return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
// holder.idTv.setText(data.get(position).getId());
holder.idTv.setText(data.get(position).getId()+"");
holder.titleTv.setText(data.get(position).getTitle());
holder.bodyTv.setText(data.get(position).getBody());
}

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

class MyViewHolder extends RecyclerView.ViewHolder{

TextView idTv,titleTv,bodyTv;

public MyViewHolder(@NonNull View itemView) {
super(itemView);
idTv= itemView.findViewById(R.id.id);
titleTv= itemView.findViewById(R.id.title);
bodyTv= itemView.findViewById(R.id.body);
}
}
}


9. Now here is MainActivity Code

public class MainActivity extends AppCompatActivity {

ProgressBar progressBar;
RecyclerView recyclerView;


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


recyclerView = findViewById(R.id.recyclerView);

progressBar =findViewById(R.id.progressBar);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
processData();


}

void processData(){

Call<List<model>> call = Controler
.getInstance()
.getapi()
.getdata();

call.enqueue(new Callback<List<model>>() {
@Override
public void onResponse(Call<List<model>> call, Response<List<model>> response) {
List<model> data = response.body();
RecAdapter adapter = new RecAdapter(data);
recyclerView.setAdapter(adapter);




progressBar.setVisibility(View.INVISIBLE);

}

@Override
public void onFailure(Call<List<model>> call, Throwable t) {

Toast.makeText(MainActivity.this, getApplicationContext().toString(), Toast.LENGTH_SHORT).show();
}
});
}
}


                

                              RUN YOUR CODE



#Retrofit #Api #json #RetrofitJosn #androidRetrofitTutorial #howToUseRetrofitAndroidStudio




Comments

Popular posts from this blog

 CLICK HERE TO DOWNLOAD

Internet of Things (IoT): What Is It and How Does It Work?

Internet of Things (IoT): What Is It and How Does It Work?   The Internet of Things (IoT) refers to a network of physical devices, vehicles, appliances, and other objects that are embedded with sensors, software, and connectivity capabilities. These devices can collect and exchange data over the internet, enabling them to interact with each other and with humans. In simpler terms, IoT is about connecting everyday objects to the internet and enabling them to communicate and share information. This connectivity allows for data to be gathered, analyzed, and used to make intelligent decisions or trigger actions. Components of IoT: 1. Devices and Sensors: IoT devices are equipped with sensors that can collect various types of data such as temperature, humidity, light, motion, and more. These devices can be anything from household appliances and wearable devices to industrial machinery and vehicles. 2. Connectivity: IoT devices rely on connectivity to transmit and receive data. This can ...

How To Use Drawable Importer In Android Studio Chipmunk 2021.2.1 | Android Fox Arctic 2020 Or +

  How To Use  Drawable Importer In Android  Fox Arctic                2020.3.2 Or + Download Drawable Importer From Below Link Open Android Studio Go to Setting Go to Plugin  Click on Right Side Sitting Icon  Click On Install Plugin From Disk Select Drawable Importer that you are Downloaded Restart The IDE Enjoy Drawable Importer                                              Download Here 👇👇👇 Stack Over Flow Questions: Android Drawable Importer plugin not working in Android Studio Chipmunk 2021.2.1 Android Drawable Importer plugin not working in Android ... 26 Feb 2020 Has anyone identified how to install "Android Drawable Import ... 13 Jun 2022 Android Drawable Importer not working in Android Studio 30 Mar 2020...