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>






Tuesday, 6 December 2016

Three Level Exapandable ListView In Android with Two level Indicators

Java:
package zaihuishou.com.expandablerecyclerview;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import zaihuishou.com.expandablerecyclerview.loader.listener.ServiceResponseListener;
import zaihuishou.com.expandablerecyclerview.loader.manager.ServiceManager;
import zaihuishou.com.expandablerecyclerview.navcategory.FirstLevelCategory;
import zaihuishou.com.expandablerecyclerview.navcategory.NavigationGategoryBaseResponse;
import zaihuishou.com.expandablerecyclerview.navcategory.SecondLevelCategory;

public class TestActivity extends AppCompatActivity {
    private ExpandableListView expandableListView;
    private Context context;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        context = this;
        expandableListView = (ExpandableListView) findViewById(R.id.mainList);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            expandableListView.setIndicatorBounds(width - GetPixelFromDips(50), width - GetPixelFromDips(10));
        } else {
            expandableListView.setIndicatorBoundsRelative(width - GetPixelFromDips(50), width - GetPixelFromDips(10));
        }
        addNavigationList();
    }

    public int GetPixelFromDips(float pixels) {
        // Get the screen's density scale        final float scale = getResources().getDisplayMetrics().density;
        // Convert the dps to pixels, based on density scale        return (int) ((scale * pixels + 0.5f) - 5);
    }

    public void addNavigationList() {
        ServiceManager.navigationList(getApplicationContext(), new ServiceResponseListener<NavigationGategoryBaseResponse>() {
                    @Override                    public void onSuccess(NavigationGategoryBaseResponse response) {
                        expandableListView.setAdapter(new TestActivity.ParentLevel(context, response.getMainCategories()));
                    }

                    @Override                    public void onFailure(Throwable throwable, String errorResponse) {

                    }
                }
        );
    }


    public class ParentLevel extends BaseExpandableListAdapter {

        private Context context;
        private List<FirstLevelCategory> firstLevelCategories;

        public ParentLevel(Context context, List<FirstLevelCategory> firstLevelCategoryList) {
            this.context = context;
            this.firstLevelCategories = firstLevelCategoryList;
        }

        @Override        public Object getChild(int arg0, int arg1) {
            return arg1;
        }

        @Override        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            TestActivity.SecondLevelExpandableListView secondLevelELV = new TestActivity.SecondLevelExpandableListView(TestActivity.this);
            secondLevelELV.setAdapter(new TestActivity.SecondLevelAdapter(context, firstLevelCategories.get(groupPosition).getSubGrouphs().get(childPosition)));
            secondLevelELV.setGroupIndicator(getResources().getDrawable(R.drawable.settings_selector));
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int width = metrics.widthPixels;
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
                secondLevelELV.setIndicatorBounds(width - GetPixelFromDips(50), width - GetPixelFromDips(10));
            } else {
                secondLevelELV.setIndicatorBoundsRelative(width - GetPixelFromDips(50), width - GetPixelFromDips(10));
            }
            return secondLevelELV;
        }

        @Override        public int getChildrenCount(int groupPosition) {
            return firstLevelCategories.get(groupPosition).getSubGrouphs().size();
        }

        @Override        public Object getGroup(int groupPosition) {
            return groupPosition;
        }

        @Override        public int getGroupCount() {
            return firstLevelCategories.size();
        }

        @Override        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override        public View getGroupView(int groupPosition, final boolean isExpanded, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.row_first, null);
                TextView text = (TextView) convertView.findViewById(R.id.eventsListEventRowText);
                final ImageView icon = (ImageView) convertView.findViewById(R.id.icon);

                String name = firstLevelCategories.get(groupPosition).getCategoryname();
                if (name.equals(context.getString(R.string.Fancy))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.fancy));
                } else if (name.equals(context.getString(R.string.Women))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.women));
                } else if (name.equals(context.getString(R.string.Office))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.stationary));
                } else if (name.equals(context.getString(R.string.BooksMore))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.books));
                } else if (name.equals(context.getString(R.string.Men))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.businessman));
                } else if (name.equals(context.getString(R.string.DailyNeeds))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.calendar));
                } else if (name.equals(context.getString(R.string.Garments))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.garments));
                } else if (name.equals(context.getString(R.string.BabyKids))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.babykids));
                } else if (name.equals(context.getString(R.string.Fashion))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.fasion));
                } else if (name.equals(context.getString(R.string.Electronics))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.elctronics));
                }
                text.setText(name);
            }
            return convertView;
        }

        @Override        public boolean hasStableIds() {
            return true;
        }

        @Override        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }

    public class SecondLevelExpandableListView extends ExpandableListView {


        public SecondLevelExpandableListView(Context context) {
            super(context);
        }

        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(999999, MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    public class SecondLevelAdapter extends BaseExpandableListAdapter {

        private Context context;
        private SecondLevelCategory secondLevelCategories;

        public SecondLevelAdapter(Context context, SecondLevelCategory secondLevelCategories) {
            this.context = context;
            this.secondLevelCategories = secondLevelCategories;
        }

        @Override        public Object getGroup(int groupPosition) {
            return groupPosition;
        }

        @Override        public int getGroupCount() {
            return 1;
        }

        @Override        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.row_third, null);
                TextView text = (TextView) convertView.findViewById(R.id.eventsListEventRowText);
                text.setText(secondLevelCategories.getSubcategoryname());
            }
            return convertView;
        }

        @Override        public Object getChild(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.row_second, null);
                TextView text = (TextView) convertView.findViewById(R.id.eventsListEventRowText);
                text.setText(secondLevelCategories.getThirdLevelCategoryList().get(childPosition).getLowersubcategoryname());
            }
            return convertView;
        }

        @Override        public int getChildrenCount(int groupPosition) {
            return secondLevelCategories.getThirdLevelCategoryList().size();
        }

        @Override        public boolean hasStableIds() {
            return true;
        }

        @Override        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
}

main.Xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/activity_test"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="zaihuishou.com.expandablerecyclerview.TestActivity"><ExpandableListViewandroid:id="@+id/mainList"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#ffffff"android:groupIndicator="@drawable/settings_selector"android:transcriptMode="alwaysScroll"></ExpandableListView></RelativeLayout>
rowfirst.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="100dp"android:orientation="horizontal"android:padding="10dp"><ImageViewandroid:id="@+id/icon"android:layout_width="25dp"android:layout_height="25dp"android:layout_alignParentLeft="true" /><TextViewandroid:id="@+id/eventsListEventRowText"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_toLeftOf="@+id/plus"android:layout_toRightOf="@+id/icon"android:textColor="@android:color/background_dark"android:textSize="15sp" /></LinearLayout>
rowsecond.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:padding="10dp"><TextViewandroid:id="@+id/eventsListEventRowText"android:layout_width="match_parent"android:layout_height="wrap_content"android:paddingLeft="20dp" /></LinearLayout>

rowthird.xml:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:padding="10dp"><TextViewandroid:id="@+id/eventsListEventRowText"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>


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