Hi Guys, Welcome to Proto Coders Point, if you have seen our last post on how to make an android http request call using okhttp android library, where we have just fetched data from the API which is in JSON format, and just displayed the response.body() in text view.
In this Tutorial post we will show/display the data received by okhttp call a http response data in Simple Listview Adapter.
DEMO SCREENSHOT
Please check out the part 1 of OkHttp android library
In part one all the required dependencies is add.
Then, Let’s start implement okhttp android response data to display in listview.
Step1: Create a layout file
res > layout (right click) >New > Layout Resource File
create a new layout file and name it as listview_layout.xml and then paste the below layout design xml UI code.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="120dp" android:weightSum="2" android:padding="2dp" android:layout_margin="10dp" android:orientation="vertical"> <TextView android:id="@+id/name" android:text="Name" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:layout_weight="0.5" android:textSize="18sp" android:textStyle="bold" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="@color/colorPrimary" /> <TextView android:id="@+id/power" android:text="Power" android:layout_weight="0.5" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#5d5d5d" /> </LinearLayout> </LinearLayout>
The above XML layout has 2 views Both are TextView which holds the name of superhero and power of the superhero.
don’t get confused i have a API of Superheros list which is in JSON format.
This is the URL of my API
https://protocoderspoint.com/jsondata/superheros.json
Step 2: adding listview in activity_main.xml
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listview"/> </androidx.constraintlayout.widget.ConstraintLayout>
this is where the list of data will be shown using ListView
Step 3 : Final MainActivity.java
MainActivity.java
package com.protocoderspoint.androidokhttp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import com.squareup.picasso.Picasso; import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { String myResponse; ListView lv; ArrayList<HashMap<String,String>> arrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); arrayList=new ArrayList<>(); lv = (ListView)findViewById(R.id.listview); OkHttpClient client = new OkHttpClient(); String url = "https://protocoderspoint.com/jsondata/superheros.json"; Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { e.printStackTrace(); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { if(response.isSuccessful()) { myResponse = response.body().string(); MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { try { JSONObject reader = new JSONObject(myResponse); JSONArray superheros = reader.getJSONArray("superheros"); // get the whole json array list System.out.println("json size is : "+superheros.length()); for(int i = 0;i<superheros.length();i++) { JSONObject hero = superheros.getJSONObject(i); String name = hero.getString("name"); String power = hero.getString("power"); System.out.println(i+" Name: "+name +" Power : "+power); HashMap<String,String> data = new HashMap<>(); data.put("name",name); data.put("power",power); arrayList.add(data); ListAdapter adapter = new SimpleAdapter(MainActivity.this,arrayList,R.layout.listview_layout ,new String[]{"name","power"},new int[]{R.id.name,R.id.power}); lv.setAdapter(adapter); } } catch (JSONException e) { e.printStackTrace(); } } }); } } }); } }
Brief detail about above source code
As we get Response using okHttp android library,
Then we are parsing the data using JSON Parser
ArrayList HashMap as a String data
ArrayList<HashMap<String,String>> arrayList; arrayList=new ArrayList<>();
arraylist will store all the data individually
String myResponse
myResponse = response.body().string();
Here is where we will hold the response.body() received from server API.
Get the JSONObject and JSONArray
JSONObject reader = new JSONObject(myResponse); JSONArray superheros = reader.getJSONArray("superheros");
Then, Here we gonna trace the json data using JSONArray
looping through all the individual data
for(int i = 0;i<superheros.length();i++) { JSONObject hero = superheros.getJSONObject(i); String name = hero.getString("name"); String power = hero.getString("power"); System.out.println(i+" Name: "+name +" Power : "+power); HashMap<String,String> data = new HashMap<>(); data.put("name",name); data.put("power",power); arrayList.add(data); ListAdapter adapter = new SimpleAdapter(MainActivity.this,arrayList,R.layout.listview_layout ,new String[]{"name","power"},new int[]{R.id.name,R.id.power}); lv.setAdapter(adapter); }Download from Google Drive
Guys, is you face any kind of problem, then feel free to contact_me