Saturday 10 August 2019

Android ListView With Multiple Items






Step 1: Create A List Item Layout File 



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_margin="5dp"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Id: "
        android:textStyle="bold"
        android:textSize="17sp"
        android:id="@+id/tv_id"/>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@mipmap/ic_launcher_round"/>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_marginLeft="5dp"
            android:layout_weight="1">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hello: "
                android:textColor="@android:color/black"
                android:textStyle="bold"
                android:textSize="17sp"
                android:id="@+id/tv_name"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Hello: "
                android:textColor="@android:color/black"
                android:textSize="15sp"
                android:id="@+id/tv_descr"/>
        </LinearLayout>
    </LinearLayout>


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Price: "
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:textSize="17sp"
        android:id="@+id/tv_price"/>


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp">


        <TextView
            android:layout_width="1.1in"
            android:layout_height="wrap_content"
            android:text="Category Id: "
            android:textSize="15sp"
            android:id="@+id/tv_catid"
            android:layout_alignParentLeft="true"/>

        <TextView
            android:layout_width="1.1in"
            android:layout_height="wrap_content"
            android:text="Category Name: "
            android:textSize="15sp"
            android:id="@+id/tv_catname"
            android:layout_alignParentRight="true"/>
    </RelativeLayout>


</LinearLayout>


Step 2: Create A DataModel Class (POJO)

As per which kind of data you want to load,
in my case my formate from my api is data is:

 {
"id": "id",
"name": "Name",
"description": "Description",
"price": "Price",
"category_id": "Category ID",
"category_name": Category Name"
 }

public class DataModel {
    String id;
    String name;
    String description;
    String price;
    String category_id;
    String category_name;

    public DataModel() {
    }

    public void setId(String id) {
        this.id = id;
    }

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

    public void setDescription(String description) {
        this.description = description;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public void setCategory_id(String category_id) {
        this.category_id = category_id;
    }

    public void setCategory_name(String category_name) {
        this.category_name = category_name;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public String getPrice() {
        return price;
    }

    public String getCategory_id() {
        return category_id;
    }

    public String getCategory_name() {
        return category_name;
    }
}

Step 3: Create A DataAdapter Class

In Adapter class we bind ui and data in app


public class DataAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<DataModel> dataModels;

    public DataAdapter(Context context, ArrayList<DataModel> dataModels) {
        this.context = context;
        this.dataModels = dataModels;
    }

    @Override
    public int getCount() {
        return dataModels.size();
    }

    @Override
    public Object getItem(int position) {
        return dataModels.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.card, null, true);

            holder.tv_id = (TextView) convertView.findViewById(R.id.tv_id);
            holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            holder.tv_descr = (TextView) convertView.findViewById(R.id.tv_descr);
            holder.tv_price = (TextView) convertView.findViewById(R.id.tv_price);
            holder.tv_catid = (TextView) convertView.findViewById(R.id.tv_catid);
            holder.tv_catname = (TextView) convertView.findViewById(R.id.tv_catname);

            convertView.setTag(holder);
        }else {

            holder = (ViewHolder)convertView.getTag();

        }

        holder.tv_id.setText("Id: " + dataModels.get(position).getId());
        holder.tv_name.setText(dataModels.get(position).getName());
        holder.tv_descr.setText(dataModels.get(position).getDescription());
        holder.tv_price.setText("Price:" + dataModels.get(position).getPrice());
        holder.tv_catid.setText("Cat Id" + dataModels.get(position).getCategory_id());
        holder.tv_catname.setText("Cat Name:" + dataModels.get(position).getCategory_name());
        return convertView;
    }

    private class ViewHolder {

        protected TextView tv_id, tv_name, tv_descr, tv_price, tv_catid, tv_catname;

    }


}


Step 4. Making Final UI Changes

For this, you need to replace your existing code of activity_main.xml with the following one

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"/>

</RelativeLayout>


After this, write down the below code snippet in MainActivity.java file.

public class MainActivity extends AppCompatActivity {
    
    private ListView listview;
    private ArrayList<DataModel> dataModelArrayList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        
        listview = (ListView) findViewById(R.id.listview);

        Retrofit get_retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Api api = get_retrofit.create(Api.class);

        Call<ResponseBody> call = api.getCatList();

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    try {

                        JSONArray jsonArray = new JSONArray(response.body().string());
                        String[] listItem = new String[jsonArray.length()];
                        //listItem = getResources().getStringArray(R.array.array_technology);
                        ArrayList<DataModel> list = new ArrayList<>();
                        for(int i = 0; i< jsonArray.length(); i++){
                            //listItem[i] = jsonArray.getJSONObject(i).getString("name");
                            DataModel data = new DataModel();
                            data.setId(jsonArray.getJSONObject(i).getString("id"));
                            data.setName(jsonArray.getJSONObject(i).getString("name"));
                            data.setDescription(jsonArray.getJSONObject(i).getString("description"));
                            data.setCategory_name(jsonArray.getJSONObject(i).getString("category_name"));
                            data.setPrice(jsonArray.getJSONObject(i).getString("price"));

                            list.add(data);
                        }

                       dataModelArrayList = list;
                       
                       DataAdapter adapter = new DataAdapter(MainActivity.this, dataModelArrayList);
                       listview.setAdapter(adapter);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }catch (Exception ex) {
                    ex.printStackTrace();
                    Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t)
            {
                t.printStackTrace();
                Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

No comments:

Android Studio - Get Current Latitude And Longitude

1. Add this dependencies in your gradle file     implementation 'com.google.android.gms:play-services-location:18.0.0' 2. Add this p...