Saturday 1 April 2017

Dyanamic ImageLoading in Android RecyclerView

Step 1:
gradle
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support:design:25.0.1'
compile 'com.android.support:support-v4:25.0.1'
compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'




Step 2:

Manifests


<!-- if you want to load images from the internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- if you want to load images from a file OR from the internet -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


<application    android:name=".ApplicationName"
    android:allowBackup="true"    
android:icon="@mipmap/ic_launcher"  
  android:label="@string/app_name"
    android:supportsRtl="true"    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
   
</application>




Step3:
Java File:
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.Base64;
import android.util.Log;

import com.fastxpo.android.fnbdelivery.utils.Utils;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;



/** * Created by karthic on 18-12-2015. */public class ApplicationName extends Application {
    public static String deviceId;

    @Override    public void onCreate() {
        super.onCreate();
        initImageLoader(getApplicationContext());
        LoadDeviceId();

        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.gurubhai.fast",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:",md+ Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }
    }


    public static void initImageLoader(Context context) {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new SHA256FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .build();
        ImageLoader.getInstance().init(config);
    }

}




ImageDownloaderListener.java:


import android.graphics.Bitmap;

public interface ImageDownloaderListener {
    public void imageDownloadComplete(Bitmap bitmap);

    public void imageDownloadFailed();
}




ImageLoader.java:
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import com.fastxpo.android.fnbdelivery.common.ApiConstants;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

public class ImageLoader {
    private com.nostra13.universalimageloader.core.ImageLoader imageLoader;
    private DisplayImageOptions options;
    private ImageDownloaderListener imageDownloaderListener;

    public ImageLoader(int onLoading, int onFailed) {
        try {
            imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
            options = new DisplayImageOptions.Builder()
                    .showImageOnLoading(onLoading)
                    .showImageForEmptyUri(onFailed)
                    .showImageOnFail(onFailed)
                    .cacheInMemory(true)
                    .cacheOnDisc(true)
                    .considerExifParams(true)
                    .bitmapConfig(Bitmap.Config.ARGB_8888)
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void displayImage(String url, ImageView imageView) {
        imageLoader.displayImage(ApiConstants.SERVER_URL + ApiConstants.IMAGEPATH + url, imageView, options);
    }

    public Bitmap getBitmap(String imageUrl) {
        final Bitmap[] bitmap = {null};
        imageLoader.loadImage(imageUrl, new ImageLoadingListener() {

            @Override            public void onLoadingStarted(String imageUri, View view) {
            }

            @Override            public void onLoadingFailed(String imageUri, View view,
                                        FailReason failReason) {
                if (imageDownloaderListener != null) {
                    imageDownloaderListener.imageDownloadFailed();
                }
            }

            @Override            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                if (imageDownloaderListener != null) {
                    imageDownloaderListener.imageDownloadComplete(loadedImage);
                    bitmap[0] = loadedImage;
                }
            }

            @Override            public void onLoadingCancelled(String imageUri, View view) {
                if (imageDownloaderListener != null) {
                    imageDownloaderListener.imageDownloadFailed();
                }
            }
        });
        return bitmap[0];
    }

    public void pause() {
        imageLoader.pause();
    }

    public void resume() {
        imageLoader.resume();
    }

    public void clearCache() {
        imageLoader.clearDiscCache();
        imageLoader.clearMemoryCache();
    }

    public void stop() {
        imageLoader.stop();
    }


}


SHA256FileNameGenerator.java
import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
import com.nostra13.universalimageloader.utils.L;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA256FileNameGenerator implements FileNameGenerator {

   private static final String HASH_ALGORITHM = "SHA256";
   private static final int RADIX = 10 + 26; // 10 digits + 26 letters
   @Override   public String generate(String imageUri) {
      byte[] sha256 = getSHA256(imageUri.getBytes());
      BigInteger bi = new BigInteger(sha256).abs();
      return bi.toString(RADIX);
   }

   private byte[] getSHA256(byte[] data) {
      byte[] hash = null;
      try {
         MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
         digest.update(data);
         hash = digest.digest();
      } catch (NoSuchAlgorithmException e) {
         L.e(e);
      }
      return hash;
   }

}




MainActivity.java
package com.fastxpo.android.fnbdelivery.activity;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.fastxpo.android.fnbdelivery.R;
import com.fastxpo.android.fnbdelivery.adapter.CartAdapter;
import com.fastxpo.android.fnbdelivery.bean.orders.LineItem;
import com.fastxpo.android.fnbdelivery.sqlite.SqliteDBHandler;
import java.util.List;
public class MainActivityextends AppCompatActivity {

    RecyclerView cartRecyclerView;
    Activity activity;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity = this;
        mainRecyclerView = (RecyclerView) findViewById(R.id.mainRecyclerView);
       
        List<LineItem> allLineItems = getAllList();
        if (allLineItems.size() > 0) {
            mainRecyclerView.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
            MainAdapter mainAdapter = new MainAdapter(activity, allLineItems);
            mainRecyclerView.setAdapter(mainAdapter );
        } else {
            Toast.makeText(activity, "main List Empty", Toast.LENGTH_SHORT).show();
        }
    }
}
MainAdapter.java
package com.fastxpo.android.fnbdelivery.adapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.fastxpo.android.fnbdelivery.R;
import com.fastxpo.android.fnbdelivery.api.manager.ImageLoader;
import com.fastxpo.android.fnbdelivery.bean.orders.LineItem;
import java.util.List;

/** * Created by karthic on 1/4/2017. */
public class MainAdapterextends RecyclerView.Adapter<MainAdapter.MyViewHolder> {

    private Context context;
    private List<LineItem> lineItemList = null;
    private ImageLoader imageLoader;

    public MainAdapter(Context context, List<LineItem> mainDataList) {

        this.context = context;
        this.lineItemList = mainDataList;
        imageLoader = new ImageLoader(R.drawable.loading, R.drawable.loading);
    }


    public static class MyViewHolder extends RecyclerView.ViewHolder {

        protected TextView name;
        protected TextView number;
        protected ImageView image;
        protected LinearLayout relativeLayout;

        public MyViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.productnameTable);
            number = (TextView) itemView.findViewById(R.id.priceTv);
            image = (ImageView) itemView.findViewById(R.id.contactimage);
            relativeLayout = (LinearLayout) itemView.findViewById(R.id.llRelativeLayout);
        }
    }

    @Override    public MainAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_row, parent, false);
        MainAdapter.MyViewHolder myViewHolder = new MainAdapter.MyViewHolder(view);

        return myViewHolder;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override    public void onBindViewHolder(final MainAdapter.MyViewHolder holder, final int position) {

   
        holder.name.setText(lineItemList.get(position).getItemname());
        holder.number.setText("S$" + lineItemList.get(position).getSellprice());

        if (!TextUtils.isEmpty(lineItemList.get(position).getImagename())) {
            String imgURL = lineItemList.get(position).getImagename();
            imageLoader.displayImage(imgURL, holder.image);
        } else {
            holder.image.setImageDrawable(context.getResources().getDrawable(R.drawable.loading));
        }

    }

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

}


product_row.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/llRelativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="2dp"
android:background="@color/white"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="80dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:id="@+id/imagell"
android:layout_alignParentLeft="true"
android:layout_height="80dp">
<ImageView
android:id="@+id/contactimage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginRight="@dimen/margin5dp"
android:contentDescription="@string/app_name" />
<TextView
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_alignParentRight="true"
android:background="@drawable/circle"
android:textColor="@color/white"
android:gravity="center"
android:textStyle="bold"
android:text="New"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_toLeftOf="@+id/checkedimageLL"
android:layout_toRightOf="@+id/imagell">
<TextView
android:id="@+id/productnameTable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:textIsSelectable="false"
android:textSize="15dp"
android:textStyle="bold" />
<TextView
android:id="@+id/priceTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/productnameTable"
android:singleLine="true"
android:textColor="@color/blactransparent"
android:textIsSelectable="false"
android:textSize="12dp" />
</RelativeLayout>
</RelativeLayout>
</LinearLayout>






No comments:

Post a Comment

Send Whatsapp Message via PHP Code

  How to Send and Receive Messages in WhatsApp using PHP In this tutorial you will see How to Send and Receive Messages in WhatsApp using PH...