How to get String in response using Retrofit 2? Retrofit Android example

Today we are going to look at another awesome library Retrofitto make the http calls. Retrofit is denitely the better alternative to volley in terms of ease of use, performance, extensibility and other things. It is a type-­safe REST client for Android built by Square. Using this tool android developer can make all network stuff much more easier. As an example, we are going to download some json and show it in RecyclerView as a list.

retrofit get api example
Retrofit get api example

 Follow those steps:-

1.Add the permission to access internet in the AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="demo.mukesh.app.com.myapplication">

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

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>

</manifest>


2.Open build.gradle and add Retrofit, Gson dependencies

dependencies {

    implementation 'com.android.support:recyclerview-v7:27.1.1'
//retrofit, gson
   
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
   
implementation 'com.google.code.gson:gson:2.6.2'
   
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.1.0' 
}

First, we need to know what type of JSON response we will be receiving


 3.Creating Model Class


public class Test {
    @SerializedName("userId")
    @Expose
    private Integer userId;
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("body")
    @Expose
    private String body;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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. Let’s see how our APIInterface.java class looks like

public interface APIInterface {

   
@GET("posts")
Call<String> getAllList();
}

5.Create APIClient.java Setting Up the Retrofit Interface
 
public class APIClient {
    private static String BASE_URL="https://jsonplaceholder.typicode.com/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        return retrofit;
    }

}


6. MyAdapter.java

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private ArrayList<Test> arrTest;

public MyAdapter(Context context, ArrayList<Test> arrTest) {
this.context = context;
this.arrTest = arrTest;

}

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

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
Test test= arrTest.get(position);
holder.title.setText(test.getTitle());
holder.desc.setText(test.getBody());

}

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

public class MyViewHolder extends RecyclerView.ViewHolder {
TextView title,desc;

public MyViewHolder(View itemView) {
super(itemView);
title=(TextView)itemView.findViewById(R.id.tvTitle);
desc=(TextView)itemView.findViewById(R.id.tvDesc);
}
}
}
 
7.MainActivity.java
 
public class MainActivity extends AppCompatActivity {
private ArrayList<Test> arrTest;
private Activity activity;
private RecyclerView recyclerView;
private MyAdapter adapter;

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

private void getAllList() {
APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
Call<String> call = apiInterface.getAllList();
call.enqueue(new Callback<String>() {
@Override public void onResponse(Call<String> call, Response<String> response) {
if (response != null) {
String data = response.body();
Type type = new TypeToken<ArrayList<Test>>() {}.getType();
arrTest = new Gson().fromJson(data, type);
initRecycler();
}
}

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

}
});
}

private void initRecycler() {
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager mLayout = new LinearLayoutManager(activity);
recyclerView.setLayoutManager(mLayout);
adapter = new MyAdapter(activity, arrTest);
recyclerView.setAdapter(adapter);
}
}

 



Disqus Comments