Thursday, 29 August 2019

Android Staggered Layout With RecyclerView




1) Add this dependencies in your gradle file


implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'

Glide is an Image Loader Library for Android developed by bumptech and is a library that is recommended by Google. It has been used in many Google open source projects including Google I/O 2014 official application. It provides animated GIF support and handles image loading/caching.

2) create staggerd_layout.xml in res/layout folder

staggerd_layout.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_margin="5dp">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="4dp"
        app:cardElevation="2dp"
        android:layout_centerHorizontal="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="5dp">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:src="@mipmap/ic_launcher"
                android:id="@+id/imageview_widget"
                android:scaleType="center"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Canada"
                android:id="@+id/name_widget"
                android:layout_below="@+id/imageview_widget"
                android:layout_marginTop="10dp"
                android:textColor="#000"/>

        </RelativeLayout>


    </androidx.cardview.widget.CardView>
</RelativeLayout>

3)Create StaggeredRecyclerViewAdapter class 

StaggeredRecyclerViewAdapter.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.util.ArrayList;


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

    private ArrayList<String> Title = new ArrayList<>();
    private ArrayList<String> ImageUrl = new ArrayList<>();
    private Context mContext;

    public StaggeredRecyclerViewAdapter(Context context, ArrayList<String> names, ArrayList<String> imageUrls) {
        Title = names;
        ImageUrl = imageUrls;
        mContext = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.staggerd_layout, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {

        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.drawable.ic_launcher_background);

        Glide.with(mContext)
                .load(ImageUrl.get(position))
                .apply(requestOptions)
                .into(holder.image);

        holder.name.setText(Title.get(position));

        holder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(mContext, Title.get(position), Toast.LENGTH_SHORT).show();
            }
        });

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder{

        ImageView image;
        TextView name;

        public ViewHolder(View itemView) {
            super(itemView);
            this.image = itemView.findViewById(R.id.imageview_widget);
            this.name = itemView.findViewById(R.id.name_widget);
        }
    }
}

4)Add RecyclerView In Your activity_main.xml file


activity_main.xml

<?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"
    android:background="@android:color/darker_gray">


    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerview"
        android:orientation="vertical"/>

</RelativeLayout>


5) Now Is Time To Implement Bind Data In MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.os.Bundle;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
 
 
    private static final int NUM_COLUMNS = 2;

    private ArrayList<String> ImageUrl = new ArrayList<>();
    private ArrayList<String> Title = new ArrayList<>();


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

        initImageBitmap();
    }

    private void initImageBitmap() {

        ImageUrl.add("http://www.transindiatravels.com/wp-content/uploads/the-taj-mahal-agra.jpg");
        Title.add("Taj Mahal");

        ImageUrl.add("https://www.planetware.com/photos-large/IND/india-top-attractions-varanasi.jpg");
        Title.add("Varanasi");

        ImageUrl.add("https://www.planetware.com/photos-large/IND/india-top-attractions-jaisalmer.jpg");
        Title.add("Jaisalmer");

        ImageUrl.add("https://www.planetware.com/photos-large/IND/india-top-attractions-gateway-india.jpg");
        Title.add("Gateway of India");

        ImageUrl.add("https://upload.wikimedia.org/wikipedia/commons/0/09/India_Gate_in_New_Delhi_03-2016.jpg");
        Title.add("India Gate");

        ImageUrl.add("https://www.planetware.com/photos-large/IND/india-top-attractions-amer-fort.jpg");
        Title.add("Amer Fort, Jaipur");

        ImageUrl.add("https://www.planetware.com/photos-large/IND/india-top-attractions-goa.jpg");
        Title.add("The Beaches of Goa");

        ImageUrl.add("https://www.planetware.com/photos-large/IND/india-top-attractions-ellora-caves.jpg");
        Title.add("The Ellora Caves, Aurangabad");

        ImageUrl.add("https://images.mapsofindia.com/my-india/qutub-minar-delhi.jpg");
        Title.add("Kutub Minar");

        ImageUrl.add("https://www.planetware.com/photos-large/IND/india-top-attractions-mysore-palace.jpg");
        Title.add("Mysore Palace");

        ImageUrl.add("https://www.planetware.com/photos-large/IND/india-top-attractions-mahabodhi-temple.jpg");
        Title.add("Mahabodhi Temple, Bodhgaya");

        initRecyclerView();
    }

    private void initRecyclerView() {

        RecyclerView recyclerView = findViewById(R.id.recyclerview);

        StaggeredRecyclerViewAdapter staggeredRecyclerViewAdapter =
                new StaggeredRecyclerViewAdapter(this, Title, ImageUrl);

        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager( NUM_COLUMNS,
                LinearLayoutManager.VERTICAL);

        /*
        Official Link Of StaggeredGridLayoutManager

  https://developer.android.com/reference/android/support/v7/widget/StaggeredGridLayoutManager

        */

        recyclerView.setLayoutManager(staggeredGridLayoutManager);
        recyclerView.setAdapter(staggeredRecyclerViewAdapter);
    }
}

Subscribe Our YouTube Channel:
Mijas Siklodi

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();
            }
        });

    }
}

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...