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

}

Wednesday, 29 January 2014

Create GIF Wallpapaer

Write below code in main xml file

<?xml version="1.0" encoding="utf-8"?>
<wallpaper xmlns:android="http://schemas.android.com/apk/res/android" />

Create raw folder in below res folder and put your GIF file in that raw folder.


Create Service Class in scr folder name MyService and write below code in that service



import java.io.IOException;
import java.io.InputStream;

import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.Handler;
import android.os.SystemClock;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.SurfaceHolder;

public class MyService extends WallpaperService {
    static final String TAG = "MyService";
    static final Handler mNyanHandler = new Handler();

    /**
     * @see android.service.wallpaper.WallpaperService#onCreate()
     */
    @Override
    public void onCreate() {
        super.onCreate();
    }

    /**
     * @see android.service.wallpaper.WallpaperService#onCreateEngine()
     */
    @Override
    public Engine onCreateEngine() {
        try {
            return new NyanEngine();
        } catch (IOException e) {
            Log.w(TAG, "Error creating NyanEngine", e);
            stopSelf();
            return null;
        }
    }

    class NyanEngine extends Engine {
        private final Movie mNyan;
        private final int mNyanDuration;
        private final Runnable mNyanNyan;
        float mScaleX;
        float mScaleY;
        int mWhen;
        long mStart;

        NyanEngine() throws IOException {
            InputStream is = getResources().openRawResource(R.raw.christmas);
            if (is != null) {
                try {
                    mNyan = Movie.decodeStream(is);
                    mNyanDuration = mNyan.duration();
                } finally {
                    is.close();
                }
            } else {
                throw new IOException("Unable to open R.raw.nyan");
            }

            mWhen = -1;
            mNyanNyan = new Runnable() {
                public void run() {
                    nyan();
                }
            };
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            mNyanHandler.removeCallbacks(mNyanNyan);
        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);
            if (visible) {
                nyan();
            } else {
                mNyanHandler.removeCallbacks(mNyanNyan);
            }
        }

        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            super.onSurfaceChanged(holder, format, width, height);
            mScaleX = width / (1f * mNyan.width());
            mScaleY = height / (1f * mNyan.height());
            nyan();
        }

        @Override
        public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep,
                float yOffsetStep, int xPixelOffset, int yPixelOffset) {
            super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
            nyan();
        }

        void nyan() {
            tick();
            SurfaceHolder surfaceHolder = getSurfaceHolder();
            Canvas canvas = null;
            try {
                canvas = surfaceHolder.lockCanvas();
                if (canvas != null) {
                    nyanNyan(canvas);
                }
            } finally {
                if (canvas != null) {
                    surfaceHolder.unlockCanvasAndPost(canvas);
                }
            }
            mNyanHandler.removeCallbacks(mNyanNyan);
            if (isVisible()) {
                mNyanHandler.postDelayed(mNyanNyan, 1000L/25L);
            }
        }

        void tick() {
            if (mWhen == -1L) {
                mWhen = 0;
                mStart = SystemClock.uptimeMillis();
            } else {
                long mDiff = SystemClock.uptimeMillis() - mStart;
                mWhen = (int) (mDiff % mNyanDuration);
            }
        }

        void nyanNyan(Canvas canvas) {
            canvas.save();
            canvas.scale(mScaleX, mScaleY);
            mNyan.setTime(mWhen);
            mNyan.draw(canvas, 0, 0);
            canvas.restore();
        }
    }
}

below is my manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gifwall"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <service
            android:label="@string/app_name"
            android:name=".MyService"
            android:permission="android.permission.BIND_WALLPAPER">
            <intent-filter>
                <action android:name="android.service.wallpaper.WallpaperService" />
            </intent-filter>
            <meta-data android:name="android.service.wallpaper" android:resource="@layout/main_xml" />
        </service>
    </application>

</manifest>

Tuesday, 3 December 2013

Add pin point on Map V2

When you have latitude and longitude then use this code

                                if(!TextUtils.isEmpty(checklat) && !TextUtils.isEmpty(checklon)){
                                        new Mybitmap().execute();
                                }


public class Mybitmap extends AsyncTask<Void, Void, Bitmap>{
        @Override
        protected Bitmap doInBackground(Void... params) {
            // TODO Auto-generated method stub
            abc = imgloader.getBitmap(checkimg);
            return abc;
        }
       
        @Override
        protected void onPostExecute(
                Bitmap result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            try{
            if(result != null){
                final LatLng latlong = new LatLng((Double.parseDouble(checklat)), (Double.parseDouble(checklon)));
                  Log.i(tag, "Latitude and Longitude ...."+latlong);
           
                  map.addMarker(new MarkerOptions()
                    .position(latlong)
                    .title(checktitle + " " +checksdateformate).icon(BitmapDescriptorFactory.fromBitmap(result)));
                map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlong, 20));
                map.animateCamera(CameraUpdateFactory.zoomTo(20), 2000, null);                                               
            }}
            catch(Exception e){
                e.printStackTrace();
            }
        }
    };

Tuesday, 15 October 2013

Set wallpaper from gallery

 final int RESULT_LOAD_IMAGE=100;

On button Click 

Intent i = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, 100);


@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
         if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
               String wallpaper = selectedWallpaperImage(getApplicationContext(),data);
               WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
             
               try {
    wallpaperManager.setBitmap(BitmapFactory.decodeFile(wallpaper));
                             //this line of code will set the selected image as your wallpaper...........
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }}
    }


public static String selectedWallpaperImage(Context context,Intent data){
             Uri selectedImage = data.getData();
     String[] filePathColumn = { MediaStore.Images.Media.DATA };

     Cursor cursor = context.getContentResolver().query(selectedImage,
             filePathColumn, null, null, null);
     cursor.moveToFirst();

     int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
     String picturePath = cursor.getString(columnIndex);
     cursor.close();
return picturePath;
}


and add permission  <uses-permission android:name="android.permission.SET_WALLPAPER" />

And if you want direct set image from application resource 

WallpaperManager myWallpaperManager = WallpaperManager
            .getInstance(getApplicationContext());
          try {
           //set wallpaper picture from resource here
           myWallpaperManager.setResource(R.drawable.andr_gp);
           Toast.makeText(getApplicationContext(),"Success set as wallpaper",22).show();
          } catch (IOException e) {
              Toast.makeText(getApplicationContext(),"Error set as wallpaper",22).show();
          } 

Image upload

When i want to upload image into web server 
 GetNameValue nv = new GetNameValue();
String signupop = chngpassop
                        .getOPName(Utility.OPERATION_NAME);


List<NameValuePair> nvp = nv.getMyInfoEditDetail(userfname,
                        userlname, usermobile, userhomephone, userworkphone,
                        userdob, strheight, strwight, streyecolor,
                        strhaircolor, strtimepref, selectedImagePath, user_id,useremail);
                if(!TextUtils.isEmpty(selectedImagePath)){
                    result = httpPost.uploadUserImage(
Utility.SIGNUP_PAGE
                            + signupop, nvp);
                }else{
                    result = httpPost.post(
Utility.SIGNUP_PAGE
                            + signupop, nvp);
                }


my http post class having function for upload image to server as define below

public String uploadUserImage(String op,List<NameValuePair> nvp)
    {
        try
        {
            HttpConnectionParams.setConnectionTimeout(params,TIMEOUT_MILLISEC);
            HttpConnectionParams.setSoTimeout(params,TIMEOUT_MILLISEC);
          
                HttpContext localContext = new BasicHttpContext();
               // System.out.println("Server Link: "+serverurl+op);
                post = new HttpPost(serverurl+op);

                try {
                    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

                    //System.out.println("Upload Image: "+nvp);
                    if(nvp != null)
                    {
                         for(int index=0; index < nvp.size(); index++)
                         {
                             if(nvp.get(index).getName().equalsIgnoreCase("user_photo"))
                            {
                                if(nvp.get(index).getName().equalsIgnoreCase("user_photo"))
                                {
                                  // If the key equals to "U_PHOTO", we use FileBody to transfer the data
                                    multipartEntity.addPart(nvp.get(index).getName(), new FileBody(new File (nvp.get(index).getValue())));
                                }
                                else
                                {
                                    // Normal string data
                                    multipartEntity.addPart(nvp.get(index).getName(), new StringBody(nvp.get(index).getValue()));
                                    }
                                 }
                             else
                             {
                                if(nvp.get(index).getName().equalsIgnoreCase("user_photo"+index))
                                {
                                    //System.out.println("---In if UMI_NAME---");
                                    multipartEntity.addPart(nvp.get(index).getName(), new FileBody(new File (nvp.get(index).getValue())));
                                }
                                else
                                {
                                    // Normal string data
                                    //System.out.println("---In else UMI_NAME---");
                                     multipartEntity.addPart(nvp.get(index).getName(), new StringBody(nvp.get(index).getValue()));
                                }
                             }
                         }
                    }
                    post.setEntity(multipartEntity);
                    response = client.execute(post, localContext);
                    entity = response.getEntity();
                    if(entity != null)
                    {
                        result = EntityUtils.toString(entity);
                    }
                    else
                    {
                        Log.d("Response Failed","Response from server is failed");
                    }
                  
                } catch (IOException e) {
                    e.printStackTrace();
                }

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

Friday, 20 September 2013

Filtering with basea adapter

this is my main activity edittext 

edtsearch.addTextChangedListener(searchTextWatcher);

make funcetion

private TextWatcher searchTextWatcher = new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if(phonebookadp != null){
                String myst = s.toString();
              
                if(myst.equalsIgnoreCase(s.toString())){
                    phonebookadp.getFilter().filter(s.toString());
                }
            }
        }
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
        public void afterTextChanged(Editable s) {}
    };


This is my adapter 

   
    public class ImportPhonebook_Adapter extends BaseAdapter implements Filterable{
      
        private LayoutInflater l_Inflater;
        Filter myFilter;

        public ImportPhonebook_Adapter(Context context) {
            l_Inflater = LayoutInflater.from(context);
        }
        public int getCount() {
            // TODO Auto-generated method stub
                return contactname.size();
        }

        public Object getItem(int position) {
            return contactname.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder holder;
            if (convertView == null) {
                convertView = l_Inflater.inflate(R.layout.contactlist, null);
                holder = new ViewHolder();
                holder.fname = (TextView) convertView.findViewById(R.id.contactlist);
                holder.lname = (TextView) convertView.findViewById(R.id.contactlistlname);
                holder.textnum = (TextView)convertView.findViewById(R.id.textnumber);
                holder.imguser = (ImageView)convertView.findViewById(R.id.imageViewuser);
                holder.chkbx = (CheckBox)convertView.findViewById(R.id.checkBox1);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.chkbx.setVisibility(View.GONE);
          
            try{
                if(contactname != null){
                    ContactSetGet contasetget = new ContactSetGet();
                    contasetget = contactname.get(position);
                  
                    cont_id = contasetget.getmyId();
                    Log.i(tag, "my cont id...."+cont_id);
                  
              
                            strmob_no = contasetget.getMainnumber();
                            if(!TextUtils.isEmpty(strmob_no)){
                                holder.textnum.setText(strmob_no);
                            }else{
                                holder.textnum.setVisibility(View.INVISIBLE);
                            }
                            strfname = contasetget.getFname();
                            strgivenname = contasetget.getLname();
                      
                              
                                if(!TextUtils.isEmpty(strfname)){
                                    holder.fname.setText(contasetget.getFname());  
                                }else{
                                    holder.fname.setVisibility(View.GONE);
                                }
                                if(!TextUtils.isEmpty(strgivenname)){
                                    holder.lname.setText(contasetget.getLname());  
                                }else{
                                    holder.lname.setVisibility(View.GONE);
                                }
                              
                            String photoId = contasetget.getPhoto();
                          
                            Log.i("Phonebook_Adapter", "image ....."+photoId);
                            if(photoId != null){
                                if(photoId.equalsIgnoreCase("00")){
                                    holder.imguser.setImageResource(R.drawable.ic_launcher);
                                }else if(photoId.contains("mnt")){
                                    Bitmap bitmap = BitmapFactory.decodeFile(photoId);
                                    holder.imguser.setImageBitmap(bitmap);
                                  
                                }
                                else{
                                    photoUri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, Long.parseLong(photoId));
                                    holder.imguser.setImageURI(photoUri);
                                }
                            }else{
                                holder.imguser.setImageResource(R.drawable.ic_contact_picture_holo_light);
                            }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return convertView;
        }
      
        @Override
        public android.widget.Filter getFilter() {
            // TODO Auto-generated method stub
            return new android.widget.Filter() {
              
                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    // TODO Auto-generated method stub
                    contactname = (ArrayList<ContactSetGet>) results.values;
                    ImportPhonebook_Adapter.this.notifyDataSetChanged();  
                }
              
                @TargetApi(Build.VERSION_CODES.GINGERBREAD)
                @SuppressLint({ "DefaultLocale", "NewApi" })
                @Override
                protected FilterResults performFiltering(CharSequence prefix) {
                    // TODO Auto-generated method stub
                    FilterResults results = new FilterResults();
                    List<ContactSetGet> i = new ArrayList<ContactSetGet>();
                  
                    String myna = prefix.toString();
                  
                    if (prefix!= null && prefix.toString().length() > 0) {

                        for (int index = 0; index < contactname.size(); index++) {
                            ContactSetGet si = contactname.get(index);
                            Log.i("----------------si.getFirstName()---------","."+si.getFname());
                            Log.i("----------------prefix---------","."+prefix.toString());
                            //String number
                          
                            myna = si.getFname().toLowerCase();
                            if(myna.startsWith(prefix.toString())){
                                Log.i(tag, "insert name..."+si.getFname());
                              i.add(si);
                            }
                        }
                        results.values = i;
                        results.count = i.size();                 
                    }
                    else{
                        synchronized (contactname){
                            results.values = mycontnamesetget;
                            results.count = mycontnamesetget.size();
                        }
                    }
                    return results;
                }
            };
        }
}


contactname is my main listview

List<ContactSetGet> mycontnamesetget;
mycontnamesetget = new ArrayList<ContactSetGet>();

fill this list same where main list fiil up
mycontnamesetget = contactname;  

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