Learning Objective: Let’s learn how to call online API and get data from the server to our Android App. We will explore it using volley.
To add Volley Library to your Android Project, Add the following code to Gradle. Reference
dependencies {
implementation 'com.android.volley:volley:1.2.1'
}
Now I would like to check out some live JSON API with sample data and I found the following URL:
https://jsonplaceholder.typicode.com/todos/1
Now Let’s add Volley code to fetch data from above URL
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
callAPI();
binding = FragmentFirstBinding.inflate(inflater, container, false);
return binding.getRoot();
}
void callAPI()
{
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getContext());
String url = "https://jsonplaceholder.typicode.com/todos/1";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("cs",response.toString());
try {
JSONObject obj = new JSONObject(response.toString());
Log.e("cs", obj.getString("userId"));
Log.e("cs", obj.getString("id"));
Log.e("cs", obj.getString("title"));
Log.e("cs", obj.getString("completed"));
} catch (Throwable t) {
Log.e("cs", "Could not parse malformed JSON: \"" + "" + "\"");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("cs",error.toString());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
output you will get it on Log Cat. Dont forget to add internet permission into your Android Manifests
<uses-permission android:name="android.permission.INTERNET" />