Reputation: 160
I am new to android programming. I am using rest call from android to query result and based on the queried result I allow user to navigate from one screen/activity to another. I have around 7 activity page and on each page I perform several operations for that I use rest call.
The way I am invoking is using AsyncHttpClient
Ex.
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://serverurl:8080/path1/path2/path3", params, new AsyncHttpResponseHandler() {
//some code
}
The one problem which I am facing is if I have to modify the url I need to modify in all the activity page.
Is there a way from where I can modify once that can be used in every activity? Is there a better way? Please let me know.
Upvotes: 2
Views: 5353
Reputation: 2768
Just use a static variable.
public class YourClass {
public static final String URL = "http://www.example.com/abc";
public void performApiCall() {
AsyncHttpClient client = new AsyncHttpClient();
client.get(URL, params, new AsyncHttpResponseHandler() {
//some code
});
}
}
You can then use the URL string from other classes:
public class SomeOtherClass {
public void performSomeOtherApiCall() {
AsyncHttpClient client = new AsyncHttpClient();
client.get(YourClass.URL, params, new AsyncHttpResponseHandler() {
//some other code
});
}
}
Upvotes: 0
Reputation: 5626
There are several ways to do API calls in your android application.
If you are worried about how to easily change the endpoint (url), you can write your code so that you pass in a string param to your methods that way, you don't hard code the value.
I am sure there are a lot more libraries out there and normally, it is a matter of choice and taste.
I hope this helps you as you try to solve your problem!
Upvotes: 1
Reputation: 1662
Use Retrofit
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
@GET("users/repos/{id}")
Call<Repo> getRepo(@Path("id") String id);
}
Any kind of url changes can be done in this interface
Initialization of retrofit with base url
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
GitHubService service = retrofit.create(GitHubService.class);
Consuming Api
Call<List<Repo>> repos = service.listRepos("octocat");
repos.enqueue(new Callback<List<Repo>>() {
@Override
public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
//Do something with response
}
@Override
public void onFailure(Call<List<String>> call, Throwable t) {
//handle failure
}
});
For more Retrofit
Upvotes: 5