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";
@Overrideprotected 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>>() {
@Override
public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {
// TODO - avoid looping
List<Message> messageList = response.body();
for (Message message : messageList) {
Log.d(TAG, new Gson().toJson(message));
}
}
@Override
public void onFailure(Call<List<Message>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Unable to fetch json: " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
No comments:
Post a Comment