Skip to content

Instantly share code, notes, and snippets.

@pprathameshmore
Created June 3, 2019 04:47
Show Gist options
  • Save pprathameshmore/11f81a84c1c75a30cbe23c6d955aa8a8 to your computer and use it in GitHub Desktop.
Save pprathameshmore/11f81a84c1c75a30cbe23c6d955aa8a8 to your computer and use it in GitHub Desktop.
package com.prathameshmore.retrofit_android;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view_result);
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Post>> listCall = jsonPlaceHolderApi.getPosts();
listCall.enqueue(new Callback<List<Post>>() {
@Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if (!response.isSuccessful()) {
textView.setText("Code " + response.code());
return;
}
List<Post> posts = response.body();
for (Post post : posts) {
String content = "";
content += "ID: " + post.getId() + "\n";
content += "User ID: " + post.getUserID() + "\n";
content += "Title: " + post.getTitle() + "\n";
content += "Body: " + post.getText() + "\n\n";
textView.append(content);
}
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
textView.setText(t.getMessage());
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment