Wednesday 2 April 2014

Image Next Previous Logic from List of Images

Make one class name ImageLoader

public class ImageLoader {

public static ArrayList<Bitmap> bitmarraylst;
Bitmap bitmap;
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
Context mContext;

public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
bitmarraylst = new ArrayList<Bitmap>();
mContext = context;
}

final int stub_id = R.drawable.defaultprofileimg;

public void DisplayImage(String url, ImageView imageView) {
// System.out.println("Getting url: "+url);

imageViews.put(imageView, url);
bitmap = memoryCache.get(url);

if (bitmap != null) {
bitmarraylst.add(bitmap);
imageView.setImageBitmap(bitmap);
} else {
queuePhoto(url, imageView);
Bitmap bitdefault = BitmapFactory.decodeResource(mContext.getResources(),stub_id);
bitmarraylst.add(bitdefault);
imageView.setImageResource(stub_id);
}


}

public void DisplayImageRounded(String url, ImageView imageView) {
// System.out.println("Getting url: "+url);

imageViews.put(imageView, url);
bitmap = memoryCache.get(url);
// bitmap = getRoundedCornerBitmap(bitmap);
if (bitmap != null)
imageView.setImageBitmap(bitmap);

else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}

private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}

public Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);

// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;

// from web
try {
Bitmap bitmap = null;
if (url.toString().length() != 0) {
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} else {
return null;
}

} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}

// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);

// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}

// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}

// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;

public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}

class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;

PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}

public void run() {
// TODO Auto-generated method stub
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
// current change for make list view Image Rounded
bmp = getRoundedCornerBitmap(bmp);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
Activity a = (Activity) photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}

// @Override
// public void run() {
// if(imageViewReused(photoToLoad))
// return;
// Bitmap bmp=getBitmap(photoToLoad.url);
// memoryCache.put(photoToLoad.url, bmp);
// if(imageViewReused(photoToLoad))
// return;
// BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
// Activity a=(Activity)photoToLoad.imageView.getContext();
// a.runOnUiThread(bd);
// }
}

boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}

// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;

public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}

public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null){
            
            
            bitmap = getRoundedCornerBitmap(bitmap);
                photoToLoad.imageView.setImageBitmap(bitmap);
            }
            else{
                photoToLoad.imageView.setImageResource(stub_id);
            }
        }
}

public void clearCache() {
memoryCache.clear();
fileCache.clear();
}

public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);

final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 12;

paint.setAntiAlias(true);
canvas.drawARGB(10, 10, 10, 10);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);

// =======================

/*
* Path clipPath = new Path(); float radius = 10.0f; float padding =
* radius / 2; int w = bitmap.getWidth(); int h = bitmap.getHeight();
* clipPath.addRoundRect(new RectF(padding, padding, w - padding, h -
* padding), radius, radius, Path.Direction.CW);
* canvas.clipPath(clipPath);
*/

return output;
}

}

================================
Make one class name BitmapWorkerTask 

public class BitmapWorkerTask extends ImageWorker {

int width = 100;
int height = 100;
NotifyImageSet mNotifyImageSet;
NotifyImageBitmap mNotifyImageBitmap;

public BitmapWorkerTask(Context context, NotifyImageSet mImageSet) {
super(context);
// TODO Auto-generated constructor stub
mNotifyImageSet = mImageSet;
}

public BitmapWorkerTask(Context context, NotifyImageBitmap mImageSet) {
super(context);
// TODO Auto-generated constructor stub
mNotifyImageBitmap = mImageSet;
}

public BitmapWorkerTask(Context context, int imageWidth, int ImageHeight) {
super(context);
// TODO Auto-generated constructor stub
width = imageWidth;
height = ImageHeight;

}

public void setWidth(int width) {
this.width = width;
}

public void setHeight(int height) {
this.height = height;
}

@Override
protected Bitmap processBitmap(Object data) {
if(data == null) return null;
// File mFile = new File(data.toString());
//     int size = width < height ? height : width;
   
//     Bitmap mBitmap = Utility.decodeFile(mFile, size);
try {
return BitmapFactory.decodeStream(new FileInputStream(new File(String.valueOf(data))), null, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}

public interface NotifyImageSet{
public void notifyImage();
}

public interface NotifyImageBitmap{
public void notifyImage(Bitmap mBitmap);
}


@Override
public void NotifyImage() {
// TODO Auto-generated method stub
if(mNotifyImageSet != null) {
mNotifyImageSet.notifyImage();
}
}

@Override
public void NotifyImageBitmap(Bitmap mBitmap) {
// TODO Auto-generated method stub
if(mNotifyImageBitmap != null) {
mNotifyImageBitmap.notifyImage(mBitmap);
}
}

}


Make one class name  FileCache

public class FileCache {
    
    private File cacheDir;
    
    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }
    
    public File getFile(String url){
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        //Another possible solution (thanks to grantland)
        //String filename = URLEncoder.encode(url);
        File f = new File(cacheDir, filename);
        return f;
        
    }
    
    public void clear(){
        File[] files=cacheDir.listFiles();
        for(File f:files)
            f.delete();
    }


}



============================
Here is your mail Images listview click

lst.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long arg3) {
// TODO Auto-generated method stub
Long bitpos = parent.getItemIdAtPosition(position);
Intent ibitmap = new Intent(Current activity.this,
next activity.class);
ibitmap.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
ibitmap.putExtra("POSITION",
Integer.parseInt(bitpos.toString()));
startActivity(ibitmap);
}
});

===================
In next activity,

int pos = 0;
ArrayList<String> arrImages = new ArrayList<String>();
private BitmapWorkerTask mImageWorker;
ProgressDialog pbrdialog;
ImageView angleimg;
Button btnprev, btnnext;
public ImageLoader imageLoader;

in oncreate() method 

Intent ibitmap = getIntent();
if (null != ibitmap.getExtras()) {
pos = this.getIntent().getExtras().getInt("POSITION");

}

imageLoader = new ImageLoader(AngleImageLoad.this);
angleimg = (ImageView) findViewById(R.id.imgtouch);
btnnext = (Button) findViewById(R.id.btnright);

btnprev = (Button) findViewById(R.id.btnleft);

mImageWorker = new BitmapWorkerTask(this, new NotifyImageBitmap() {

@Override
public void notifyImage(Bitmap mBitmap) {
// TODO Auto-generated method stub
if(mBitmap != null){
pbrdialog.cancel();
angleimg.setImageBitmap(mBitmap);
}else{
pbrdialog.cancel();
angleimg.setImageResource(R.drawable.defaultprofileimg);
}
}
});
mImageWorker.setWidth(angleimg.getWidth());

mImageWorker.setHeight(angleimg.getHeight());





get image position then make one function to display image in imageview from its position

public void displayImage() {

if (arrImages.get(pos) != null) {
pbrdialog = new ProgressDialog(AngleImageLoad.this);
pbrdialog.setMessage("Loading...");
pbrdialog.show();
mImageWorker.loadImage(arrImages.get(pos), angleimg);
}

}


then on click of next and previous buttons are

public void MyPrevios() {
if (pos > 0) {
pos--;
displayImage();
} else {
Toast.makeText(getApplicationContext(), "First Image", Toast.LENGTH_SHORT).show();
}
}

public void MyNext() {
if (pos < arrImages.size() - 1) {
pos++;
displayImage();
} else {
Toast.makeText(getApplicationContext(), "Last Image", Toast.LENGTH_SHORT)
.show();
}

}

Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...