compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
public class ApiClient { public static final String BASE_URL = "your URL"; private static Retrofit retrofit = null; public static Retrofit getClient() { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }public interface ApiInterface { @GET("Retrofit.php") Call<List<Message>> getInbox(); }public class Message { public int id; public String msg; public String url; public Message(int id, String msg, String url) { this.id = id; this.msg = msg; this.url = url; } }public class MainActivity extends AppCompatActivity { String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class); Call<List<Message>> call = apiService.getInbox(); call.enqueue(new Callback<List<Message>>() { @Overridepublic void onResponse(Call<List<Message>> call, Response<List<Message>> response) { // TODO - avoid loopingList<Message> messageList = response.body(); for (Message message : messageList) { Log.d(TAG, new Gson().toJson(message)); } } @Overridepublic void onFailure(Call<List<Message>> call, Throwable t) { Toast.makeText(getApplicationContext(), "Unable to fetch json: " + t.getMessage(), Toast.LENGTH_LONG).show(); } }); } }} }
Tuesday, June 27, 2017
[Android] Retrofit library
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment