Recycler View Part - III

Show your API response or Business Data in Recycler!

So far we've made two recycler views:

  1. List of numbers
  2. List of our string data

But we will not be passing or showing simple data as we start fetching API responses or even while showing static data our recyclers will not just show simple string or numbers.

We will be working will List of Objects or List of Classes.

Steps

1. Java Class Creation

What is Java class in Android?

"Java classes whose sole purpose is to hold data and make it accessible via getters and setters"

They hold your data model/table row/business model or any data set you like.

Example: If I am making a recycler to show a country details. I would think a country model class as

{
  "name": "Nepal",
  "country_code": "+977",
  "capital": "Kathmandu",
  "isActive":true,
  "area": 147181,
  "flag": "https://flagcdn.com/w320/np.png"
}

The above JSON is just for one country, and looking at a single JSON Object I will make a Java class as:

public class CountryModel {
    private String name;
    private String country_code;
    private String capital;
    private Boolean isActive;
    private int area;
    private String flag;
}

The above class will reflect a single JSON object. Now let's generate Constructors and Getter and Setter pressing Alt+Enter or goto Code >Generate

image.png After generating constructor and getter & setter your should look like this

public class CountryModel {
    private String name;
    private String country_code;
    private String capital;
    private Boolean isActive;
    private int area;
    private String flag;


    public CountryModel(String name, String country_code, String capital, Boolean isActive, int area, String flag) {
        this.name = name;
        this.country_code = country_code;
        this.capital = capital;
        this.isActive = isActive;
        this.area = area;
        this.flag = flag;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry_code() {
        return country_code;
    }

    public void setCountry_code(String country_code) {
        this.country_code = country_code;
    }

    public String getCapital() {
        return capital;
    }

    public void setCapital(String capital) {
        this.capital = capital;
    }

    public Boolean getActive() {
        return isActive;
    }

    public void setActive(Boolean active) {
        isActive = active;
    }

    public int getArea() {
        return area;
    }

    public void setArea(int area) {
        this.area = area;
    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }
}

Perfect! Well done!

Now since we have a model class to represent a single country we can make list of country and show it in our recycler-view

2. Create some data in MainActivity

In Part 2 we made ArrayList of String, now let's change it as ArrayList of CountryModel.

ArrayList<CountryModel> countryData = new ArrayList<>();

Also remove the data we added from Sunday to Saturday and in that space add Country Data as

  countryData.add(new CountryModel(
                "Nepal",
                "+977",
                "Kathmandu",
                true,
                1578181,
                "https://flagcdn.com/w320/np.png"
        ));

        countryData.add(new CountryModel(
                "China",
                "+86",
                "Beijing",
                true,
                9706961,
                "https://flagcdn.com/w320/cn.png"
        ));

        countryData.add(new CountryModel(
                "India",
                "+91",
                "Delhi",
                true,
                3287590,
                "https://flagcdn.com/w320/in.png"
        ));

I've added only three countries you can add as much as you want.

3. Change the Adapter to accept data

In your SimpleRecyclerViewAdapter change the global variable which was as follows


ArrayList<CountryModel> recyclerData = new ArrayList<CountryModel>();

 SimpleRecyclerAdapter(ArrayList<CountryModel> receivedData){
      recyclerData = receivedData
 }

4. Change Layout, ViewHolder and onBind

Since a single country has more than one data field which can be shown, let's change our xml design so that a single recycler item can show more than one data.

image.png

<?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:background="@color/purple_500"
    android:padding="10dp"
    android:layout_margin="10dp"
    android:layout_height="wrap_content">


    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="24dp"
        android:layout_marginBottom="24dp"
        android:text="Name"
        android:textColor="@color/white"
        android:textSize="22sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_marginTop="10dp"
        android:id="@+id/code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Code"
        android:textColor="@color/white"
        android:textSize="17sp"
        app:layout_constraintEnd_toEndOf="parent"

        app:layout_constraintStart_toEndOf="@+id/name"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_marginTop="10dp"
        app:layout_constraintTop_toBottomOf="@id/code"
        android:id="@+id/area"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Area"
        android:textColor="@color/white"
        android:textSize="19sp"
        app:layout_constraintEnd_toEndOf="@+id/code"
        app:layout_constraintStart_toStartOf="@+id/code" />
</androidx.constraintlayout.widget.ConstraintLayout>

Now let's change our ViewHolder inside the adapter. All the new fields in our recycler layout must be initialized here.

public class ViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        TextView code;
        TextView area;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.name);
            code = itemView.findViewById(R.id.code);
            area = itemView.findViewById(R.id.area);
        }
    }

After we have the views lets bind them inside onBindViewHolder

 @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.name.setText(recyclerData.get(position).getName());
        holder.code.setText(recyclerData.get(position).getCountry_code());
        holder.area.setText(recyclerData.get(position).getArea());

    }

Binding makes sure that our views which we initialized in ViewHolder will each be bonded with a value which we have provided.

That's all, build your application so you can see the list of countries with some extra information

Total Recycler Code

public class SimpleRecyclerViewAdapter
        extends
        RecyclerView.Adapter<SimpleRecyclerViewAdapter.ViewHolder> {

    ArrayList<CountryModel> recyclerData = new ArrayList<>();

    SimpleRecyclerViewAdapter(
            ArrayList<CountryModel> receivedData) {
        recyclerData = receivedData;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(
                LayoutInflater.from(
                        parent.getContext())
                        .inflate(
                                R.layout.layout_recycler_item,
                                parent,
                                false
                        )
        );
    }
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.name.setText(recyclerData.get(position).getName());
            holder.code.setText(recyclerData.get(position).getCountry_code());
            holder.area.setText(recyclerData.get(position).getArea());

        }

    @Override
    public int getItemCount() {
        return recyclerData.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        TextView code;
        TextView area;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.name);
            code = itemView.findViewById(R.id.code);
            area = itemView.findViewById(R.id.area);
        }
    }
}

Total MainActivity Code

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    LinearLayoutManager linearLayoutManager;
    SimpleRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getActionBar().hide();

        ArrayList<CountryModel> countryData = new ArrayList<>();

        countryData.add(new CountryModel(
                "Nepal",
                "+977",
                "Kathmandu",
                true,
                1578181,
                "https://flagcdn.com/w320/np.png"
        ));

        countryData.add(new CountryModel(
                "China",
                "+86",
                "Beijing",
                true,
                9706961,
                "https://flagcdn.com/w320/cn.png"
        ));

        countryData.add(new CountryModel(
                "India",
                "+91",
                "Delhi",
                true,
                3287590,
                "https://flagcdn.com/w320/in.png"
        ));

        recyclerView = findViewById(R.id.recycler_view);
        linearLayoutManager = new LinearLayoutManager(this,RecyclerView.VERTICAL, false);
        adapter = new SimpleRecyclerViewAdapter(countryData);

        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(linearLayoutManager);

    }


}

Assignment

Please upload this working project as assignment of recycler-view-part-III