Advertisements

Android picasso

Picasso is a really nice library you can use to manage images and specially while loading them. Before using Picasso i have tried to use AsyncTask to load images from a URL, but the performance was very slow and was not functioning the way i wanted my application which was FASTER Loading. 

Now in this tutorial i am going to show you how to load images from URL faster in a grid view where the URL is stored in SQL server database.

You can use any of the databases to fetch the data through select query or JSON and use this library. You can Look at the example given below to know how these images will be loaded.

Here I am loading a Bunch of images while the progress dialog appears at once but it will not affect your application performance.

Now to add picasso to your android project compile this in your app Gradle build file and sync project.

compile 'com.squareup.picasso:picasso:2.5.2'


Now to learn how make Sql server connection with your application you can check my post here and get connection class. Now you can paste following code in your resource file. We will first create a GridView.

 <GridView
        android:id="@+id/grid_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:columnWidth="110dp"
        android:gravity="center"
        android:numColumns="2"></GridView>

Now we need to make a custom grid view to add text image or any other thing you would like to add you can add it. Create another resource file item_grid_view.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/android_custom_gridview_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="5dp">

    <ImageView
        android:id="@+id/item_image"
        android:layout_width="170dp"
        android:layout_height="220dp"
        android:src="@mipmap/demo" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="5dp">

        <TextView
            android:id="@+id/txt_item"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Bath tub sun rays guffry"
            android:textColor="#2c3e50"
            android:textSize="17sp" />

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

            <TextView
                android:id="@+id/txt_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:text="@string/Rs"
                android:textColor="#c23616"
                android:textSize="16sp"
                android:textStyle="bold" />

            <ImageView
                android:id="@+id/img_share"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_marginRight="16dp"
                android:src="@drawable/share_item" />
        </RelativeLayout>
    </LinearLayout>

    <Button
        android:id="@+id/btn_checkitout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/checkitout"
        android:text="Check It Out"
        android:textColor="@color/colorwhite"
        android:textSize="13sp"
        android:textStyle="bold" />
</LinearLayout>

Now Create a custom adapter for gridview and name it as CustomGridViewItemsActivity. Here i will add code for picasso to fetch images from a URL.

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.safiyaakhtar.gifty.POJO.ItemPOJO;
import com.safiyaakhtar.gifty.R;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class CustomGridViewItemActivity extends ArrayAdapter<ItemPOJO> {
    private Context mContext;
    private int layoutResourceId;
    private ArrayList<ItemPOJO> mGridData = new ArrayList<ItemPOJO>();

    public CustomGridViewItemActivity(Context mContext, int layoutResourceId, ArrayList<ItemPOJO> mGridData) {
        super(mContext, layoutResourceId, mGridData);
        this.layoutResourceId = layoutResourceId;
        this.mContext = mContext;
        this.mGridData = mGridData;
    }

    public void setGridData(ArrayList<ItemPOJO> mGridData) {
        this.mGridData = mGridData;
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        final ViewHolder holder;
        if (row == null) {
            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            holder = new ViewHolder();
            holder.txt_itemname = (TextView) row.findViewById(R.id.txt_item);
            holder.txt_itemprice = (TextView) row.findViewById(R.id.txt_price);
            holder.item_imageView = (ImageView) row.findViewById(R.id.item_image);
           
            row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();
        }
        final ItemPOJO item = mGridData.get(position);
        holder.txt_itemname.setText(Html.fromHtml(item.getItemname()));
        holder.txt_itemprice.setText("u20B9" + Html.fromHtml(item.getItemPrice()));
        holder.txt_itemprice.setTag(Html.fromHtml(item.getItemURl()));
        Picasso.with(mContext).load(item.getItemImage()).into(holder.item_imageView);

    static class ViewHolder {
        TextView txt_itemname, txt_itemprice;
        ImageView item_imageView;
      
    
}

To get elements from Sql query i have created an ItemPojo.


public class ItemPOJO {
    public String Itemname;
    public String ItemPrice;
    public String ItemURl;

    public String getItemtypecode() {
        return Itemtypecode;
    }

    public void setItemtypecode(String itemtypecode) {
        Itemtypecode = itemtypecode;
    }

    public String Itemtypecode;

    public String getItemImage() {
        return ItemImage;
    }

    public void setItemImage(String itemImage) {
        ItemImage = itemImage;
    }

    public String ItemImage;



    public String getItemname() {
        return Itemname;
    }

    public void setItemname(String itemname) {
        Itemname = itemname;
    }

    public String getItemPrice() {
        return ItemPrice;
    }

    public void setItemPrice(String itemPrice) {
        ItemPrice = itemPrice;
    }

    public String getItemURl() {
        return ItemURl;
    }

    public void setItemURl(String itemURl) {
        ItemURl = itemURl;
    }
}

Now go to main activity. here you just have to fire your query and get required detail like URL and title or caption and send it it to the custom adapter and this will handle it all.

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import id.arieridwan.lib.PageLoader;

public class ItemsActivity extends AppCompatActivity {
    ItemPOJO itemPOJO;
    GridView gridView;
    ArrayList<ItemPOJO> mylist;
    CustomGridViewItemActivity adapter;
    ConnectionClass connectionClass;
   
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_items);
      
        gridView = (GridView) findViewById(R.id.grid_item);
    
        connectionClass = new ConnectionClass();
        ItemData doLogin = new ItemData();
        doLogin.execute();      
    
    public class ItemData extends AsyncTask<String, String, String> {
        String z = "";
        Boolean isSuccess = false;

 
        @Override
        protected void onPostExecute(String r) {
         
            if (isSuccess) {
                adapter = new CustomGridViewItemActivity(ItemsActivity.this, R.layout.item_grid_view, mylist);
                adapter.setGridData(mylist);
                gridView.setAdapter(adapter);
            } else {
                Toast.makeText(ItemsActivity.this, "Check Your Internet Connection", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                Connection con = connectionClass.CONN();
                if (con == null) {
                    z = "Check Your Internet Connection";
                } else {
                    String query = "select * from table";
                 
                    Statement stmt = con.createStatement();
                    ResultSet rs = null;
                    mylist = new ArrayList<>();
                       rs = stmt.executeQuery(query);
                    while (rs.next()) {
                        isSuccess = true;
                        itemPOJO = new ItemPOJO();
                        itemPOJO.setItemname(rs.getString("item_name"));
                        itemPOJO.setItemURl(rs.getString("Item_URL"));
                        itemPOJO.setItemPrice(rs.getString("item_price"));
                        itemPOJO.setItemImage(rs.getString("item_image"));
mylist.add(itemPOJO);
                    }
                }
            } catch (SQLException ex) {
                isSuccess = false;
                z = "Check Your Internet Connection";
            }
            return z;
        }
    }
}

Now you can run this code successfully. you have set images from URL in a custom Grid View via Picasso. Same approach can be used for recycler view or list view. If you have any problem you can ask in comment box below. Thank you and Please share and comment if you like this Post.

How useful was this post?

Do not forget to rate! this helps us to Improve.

Average rating / 5. Vote count:

Read More Like This..

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Advertisements

Safiya Akhtar

Safiya Akhtar is Android Application Developer in India. She is currently working as a public consultant for career and education too, besides blogging and freelancing. She believes that it is never too late or too early to start what you have always dreamed of.

One thought on “Android picasso

Your Views And Question are Welcome Here!

Advertisements