Thursday 8 August 2013

Get Contact name,number and photo

 public  void getNameContactDetails(){
        ContentResolver cr = getContentResolver();
        ContactSetGet contactsetgte;
        ArrayList<ContactSetGet> names = new ArrayList<ContactSetGet>();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
               null, null, null,null);
       
        if (cur.getCount() > 0) {
           while (cur.moveToNext()) {
               String cont_id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
              String cont_name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
               String photoId = cur.getString(cur.getColumnIndex(Contacts.PHOTO_ID));
                String phototjumb = cur.getString(cur.getColumnIndex(Contacts.PHOTO_THUMBNAIL_URI));
               if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                   System.out.println("name : " + cont_name + ", ID : " + cont_id);
                   System.out.println("photoId : " + photoId);
                   System.out.println("phototjumb : " + phototjumb);

                   // get the phone number
                   Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                                          ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                                          new String[]{cont_id}, null);
                   while (pCur.moveToNext()) {
                    String cont_phone = pCur.getString(
                                pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                         System.out.println("phone" + cont_phone);
                   }
                 pCur.close();
                }
           }
        }
    }


declair this method in your oncreate method


Tuesday 6 August 2013

Filter Listview with custom base adapter

If you want to filter listview item with name then follow below steps

write this code in oncreate method of your main activity

edtsearch.addTextChangedListener(searchTextWatcher);
(here edtsearch is your edittext,searchTextWatcher is method define outside oncreate method)

create method outside oncreate method of your main activity

private TextWatcher searchTextWatcher = new TextWatcher() {
        @SuppressWarnings("static-access")
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if(phonebookadp != null){
                phonebookadp.getFilter().filter(s.toString());   
            }
        }
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
        public void afterTextChanged(Editable s) {}
    };


here phonebookadp is your adapter.

here declaired adapter in your main activity 

    public class Phonebook_Adapter extends BaseAdapter implements Filterable{

        private LayoutInflater l_Inflater;

        public Phonebook_Adapter(Context context) {
            l_Inflater = LayoutInflater.from(context);

            // this is new array list if we click on backpress so fill listview back with this arraylist
            // fill this array list where mylstcont list filling
            mycheckcontlst = new ArrayList<String>();
        }
        public int getCount() {
            // TODO Auto-generated method stub

            // this is your list view items
            return mylstcont.size();
        }

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

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

        public View getView(final int position, View convertView, ViewGroup parent) {
          
            // Do yout stuff

            return convertView;
        }
   
        @Override
        public Filter getFilter() {
            // TODO Auto-generated method stub
            return new Filter(){
              
                // ContactSetGet is your gettersetter class

                @Override
                protected FilterResults performFiltering(CharSequence prefix) {
                    // TODO Auto-generated method stub
                    FilterResults results = new FilterResults();
                    List<ContactSetGet> i = new ArrayList<ContactSetGet>();
                  
                    if (prefix!= null && prefix.toString().length() > 0) {

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

                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint,
                        FilterResults results) {
                    // TODO Auto-generated method stub
                    mylstcont = (ArrayList<ContactSetGet>) results.values;
                        Phonebook_Adapter.this.notifyDataSetChanged();
                }
            };
    }
}


 
 

Saturday 3 August 2013

Get Json Response

You have to create some classes to get json response


for example your json url is like :- http://67.222.29.105/demo/apps/index.php/operation/active_events


create class name JsonHttpPost

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.util.Log;


public class JsonHttpPost {

String result = null;
    private static final int TIMEOUT_MILLISEC = 20000;
private static final String serverurl = "http://67.222.29.105/demo/apps/";


    HttpParams params = new BasicHttpParams();
    HttpClient client = new DefaultHttpClient(params);
    HttpResponse response;
    HttpEntity entity;
    HttpPost post;



    public String post(String operation,List<NameValuePair> nvp)
    {
        try
        {  
            HttpConnectionParams.setConnectionTimeout(params,TIMEOUT_MILLISEC);
            HttpConnectionParams.setSoTimeout(params,TIMEOUT_MILLISEC);
          
            System.out.println("Server Link: "+serverurl+operation);
            post = new HttpPost(serverurl+operation);
            if(nvp != null)
            {
                post.setEntity(new UrlEncodedFormEntity(nvp));
            }
            response = client.execute(post);
            entity = response.getEntity();
            if(entity != null)
            {
                result = EntityUtils.toString(entity);
            }
            else
            {
                Log.d("Response Failed","Response from server is failed");
            }
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
        Log.d("Json Response ","******"+result);
        return result;
    }
 


    public String deleteImage(String string)
    {
        try
        {
            HttpConnectionParams.setConnectionTimeout(params,TIMEOUT_MILLISEC);
            HttpConnectionParams.setSoTimeout(params,TIMEOUT_MILLISEC);
          
            post = new HttpPost(string);
          
            response = client.execute(post);
            entity = response.getEntity();
            if(entity != null)
            {
                result = EntityUtils.toString(entity);
            }
            else
            {
                Log.d("Response Failed","Response from server is failed");
            }
          
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return result;
    }
   
    public String deleteVideo(String string)
    {
        try
        {
            HttpConnectionParams.setConnectionTimeout(params,TIMEOUT_MILLISEC);
            HttpConnectionParams.setSoTimeout(params,TIMEOUT_MILLISEC);
          
            post = new HttpPost(string);
          
            response = client.execute(post);
            entity = response.getEntity();
            if(entity != null)
            {
                result = EntityUtils.toString(entity);
            }
            else
            {
                Log.d("Response Failed","Response from server is failed");
            }
          
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return result;
    }
   
    public String uploadImage(String op,List<NameValuePair> nvp)
    {
        try
        {
            HttpConnectionParams.setConnectionTimeout(params,TIMEOUT_MILLISEC);
            HttpConnectionParams.setSoTimeout(params,TIMEOUT_MILLISEC);
          
                HttpContext localContext = new BasicHttpContext();
                post = new HttpPost(serverurl+op);
                try {
                    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

                    if(nvp != null)
                    {
                         for(int index=0; index < nvp.size(); index++)
                         {
                             if(nvp.get(index).getName().equalsIgnoreCase("addressbook_photo"))
                            {
                                if(nvp.get(index).getName().equalsIgnoreCase("addressbook_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("addressbook_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;
      
    }
   
    public String uploadImageAddEvent(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("before_event_photo"))
                            {
                                if(nvp.get(index).getName().equalsIgnoreCase("before_event_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("before_event_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;
      
    }
   
    public String uploadAttendeeImage(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("attendee_photo"))
                            {
                                if(nvp.get(index).getName().equalsIgnoreCase("attendee_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("attendee_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;
      
    }
   
   
    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;
      
    }
   
    public String post(String request)
    {
        String result = null;
        try
        {  
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params,TIMEOUT_MILLISEC);
            HttpConnectionParams.setSoTimeout(params,TIMEOUT_MILLISEC);
          
            HttpClient client = new DefaultHttpClient(params);
          
            //System.out.println("Getting url: "+request);
            System.out.println("Server Link: "+serverurl+request);
            HttpPost post = new HttpPost(serverurl+request);
          
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            if(entity != null)
            {
                result = EntityUtils.toString(entity);
            }
            else
            {
                Log.d("Response Failed","Response from server is failed");
            }
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return result;
    }
}
 


create new class name GetOperationName 

public class GetOperationName {
   
    final String operation = "operation";
    String link;

    public String getOPName(String OPERATION_NAME) {
        // TODO Auto-generated method stub
        link = "/"+operation+"/"+OPERATION_NAME;
        return link;
    }
   
    public String getOPNameQue(String OPERATION_NAME) {
        // TODO Auto-generated method stub
        link = "/"+operation+"/"+OPERATION_NAME + "?";
        return link;
    }
   
    public String getField(String FIELD_NAME) {
        return "&"+FIELD_NAME;
    }

    public String getTwoField(String string, String string2) {
        // TODO Auto-generated method stub
        return "&"+string+"&"+string2;
    }

    public String getFourField(String string, String string2, String string3,
            String string4) {
        // TODO Auto-generated method stub
        return "&"+string+"&"+string2+"&"+string3+"&"+string4;
    }

    public String getFiveField(String string, String string2, String string3,
            String string4, String string5) {
        // TODO Auto-generated method stub
        string5 = string5.replaceAll(" ","%20");
        //System.out.println("5th string: "+string5.replaceAll(" ","%20"));
        //System.out.println("Result: "+"&"+string+"&"+string2+"&"+string3+"&"+string4+"&"+string5);
        return "&"+string+"&"+string2+"&"+string3+"&"+string4+"&"+string5;
    }

    public String getThreeField(String string, String string2, String string3) {
        // TODO Auto-generated method stub
        return "&"+string+"&"+string2+"&"+string3;
    }

    public String getEightField(String string, String string2, String string3,
            String string4, String string5, String string6, String string7,
            String string8) {
        // TODO Auto-generated method stub
        return "&"+string+"&"+string2+"&"+string3+"&"+string4+"&"+string5+"&"+string6+"&"+string7+"&"+string8;
    }

    public String getTenField(String string, String string2, String string3,
            String string4, String string5, String string6, String string7,
            String string8, String string9, String string10) {
        // TODO Auto-generated method stub
        return "&"+string+"&"+string2+"&"+string3+"&"+string4+"&"+string5+"&"+string6+"&"+string7+"&"+string8+"&"+string9+"&"+string10;
    }
}

create new class name GetNameValue

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

public class GetNameValue {

    List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
   
    public List<NameValuePair> getEventPastDetails(String struserid) {
        // TODO Auto-generated method stub
        nvp.add(new BasicNameValuePair("user_id",struserid));
        //nvp.add(new BasicNameValuePair("E_ID",struserid));
        return nvp;       
    }    

}


create class name Settings

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class Settings {
   
    public static String OPERATION_NAME = null;           
    public static final String TRUE = "True";
    public static final String NO_NETWORK = "Can not connect to internet";
    public static final CharSequence LOADING = "Loading";
     public static final String NO_RESPONSE = "Not getting data";
    public static final String LOGIN_PAGE = "index.php";
    public static final String SIGNUP_PAGE = "index.php";
   
    public static boolean isNetworkAvailable(Context context)
    {
        ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        return info!=null;
    }
}





In your main Activity on create function

this is start code for getting json response.


if(!TextUtils.isEmpty(user_id)){
            boolean chkNet =
Settings .isNetworkAvailable(context);
            if (chkNet == true) {
                ActiveEventProcess activeevent = new ActiveEventProcess();
                activeevent.execute(this);
            }           
        }



put below code out side oncreate method

declare ProgressDialog gloably above oncreate method

ProgressDialog   prodialog;


    @SuppressWarnings("rawtypes")
    public class ActiveEventProcess extends AsyncTask {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            prodialog = new ProgressDialog(context);
            prodialog.setMessage("Loading");
            prodialog.show();
            prodialog.setCancelable(false);
        }

        @Override
        protected Object doInBackground(Object... params) {
            // TODO Auto-generated method stub
            String result;
            Log.i(tag, "my user id is.." + user_id);
            try {
                JsonHttpPost httpPost = new JsonHttpPost();
                GetOperationName chngpassop = new GetOperationName();
                GetNameValue nv = new GetNameValue();

               
Settings .OPERATION_NAME = "active_events";
                String signupop = chngpassop
                        .getOPNameQue(TixeSettings.OPERATION_NAME);
                List<NameValuePair> nvp = nv.getEventPastDetails(user_id);

                result = httpPost
                        .post(
Settings .SIGNUP_PAGE + signupop, nvp);






               //If you want to upload image from json url ,and if you get image in this json response and you want to get it then use below code.
//                   result = httpPost.uploadImage(TixeSettings.SIGNUP_PAGE + //signupop, nvp);



                Log.i(tag, "result" + result);

               // here in result you got the json response

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

        @SuppressWarnings("unchecked")
        @Override
        protected void onPostExecute(Object result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            prodialog.dismiss();


               
                  //  Do your stuff here

        }
    }



Saturday 27 July 2013

Create Repeating Alarm Service

create repeating alarm service for 5 minute ,use below code in your MainActivity.class or where you want to start repeating alarm.


public static PendingIntent pendingIntentfiftyfive;
public static AlarmManager alarmManagerfiftyfive;

Intent intentser1 = new Intent(mContext, FiveMinuteService.class);
                                pendingIntentfiftyfive = PendingIntent.getService(mContext, 1, intentser1, 0);
                                alarmManagerfiftyfive = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
                                Calendar calendarser1 = Calendar.getInstance();
                                calendarser1.setTimeInMillis(System.currentTimeMillis());
                                calendarser1.add(Calendar.MINUTE, 5);
                                alarmManagerfiftyfive.setRepeating(AlarmManager.RTC_WAKEUP, calendarser1.getTimeInMillis(),5 * 60 * 1000, pendingIntentfiftyfive);



create service name FiveMinuteService

public class FiveMinuteService extends Service{

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        // try your code here
        // put your toast here
    }
   
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
        // try you code here
    }
}



now ,to cancel repeating alarm use below code                   

alarmManagerfiftyfive.cancel(pendingIntentfiftyfive);



now ,to cancel repeating alarm from other activity use below code

here MainActivity is your activity where you put your repeating alarm code.

MainActivity.alarmManagerfiftyfive.cancel(MainActivity.pendingIntentfiftyfive);


Slider example

You create slider look like in facebook.
follow below steps ,


create  horz_scroll_menu.xml file 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/menu"
    android:layout_width="1dp"
    android:layout_height="1dp"
    android:background="#2A323D"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#2A323D"
        android:scrollbars="none" >
    </ListView>

</LinearLayout>


create link.xml 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/link"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginLeft="16dp"
        android:padding="10dp"
        android:textSize="16sp"
        android:textStyle="bold"
        android:textColor="@android:color/white"
        android:text="">
    </TextView>
   
</RelativeLayout>


create screen_facebook_slider.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">

    <RelativeLayout
        android:id="@+id/tabBar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/blue_gradient_header"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/BtnSlide"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="false"
            android:layout_centerVertical="true"
            android:layout_gravity="center"
            android:layout_marginLeft="8dp"
            android:padding="4dp"
            android:background="@drawable/menu"
            android:text=""/>

        <TextView
            android:id="@+id/txtTitle"
            android:layout_width="wrap_content"
            android:layout_height="32dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="Facebook Slider"
            android:textColor="@android:color/white"
            android:textSize="22sp"
            android:textStyle="bold"
            android:typeface="sans" >

        </TextView>

     </RelativeLayout>
    <WebView 
    android:id="@+id/webView"
    android:layout_below="@+id/tabBar"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="visible"
    />

</RelativeLayout>


create screen_scroll_with_list_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<com.android.facebookslider.FacebookSlideView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="0px"
    android:background="#00ffffff"
    android:fadingEdge="none"
    android:fadingEdgeLength="0px"
    android:padding="0px"
    android:scrollbars="none" >

    <LinearLayout
        android:id="@+id/top"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_margin="0px"
        android:background="#ffffffff"
        android:orientation="horizontal"
        android:padding="0px" >
    </LinearLayout>

</com.android.facebookslider.FacebookSlideView>



create Config.class

import java.util.ArrayList;
import com.android.model.WebAddress;

public class Config {
   
    static ArrayList<WebAddress> address = null;

    public static ArrayList<WebAddress> createAddress() {
        address = new ArrayList<WebAddress>();
        address.add(new WebAddress("Google","http://www.google.com"));
        address.add(new WebAddress("Yahoo","http://www.yahoo.co.in"));
        address.add(new WebAddress("Gmail","http://www.gmail.com"));
        address.add(new WebAddress("Facebook","http://www.facebook.com"));
        address.add(new WebAddress("My Blog","http://divine4android.blogspot.in/"));
        return address;

    }

}


create WebAddress.class

public class WebAddress {
    String name;
    String url;
   
   
    public WebAddress(String name, String url) {
        this.name = name;
        this.url = url;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
   
}


create Adapter MenuAdapter.class

import java.util.ArrayList;
import com.android.model.WebAddress;
import com.example.facebookslider.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class MenuAdapter extends ArrayAdapter<WebAddress> {

    Context context;
    int layoutResourceId;  
     ArrayList<WebAddress> data=new ArrayList<WebAddress>();
    public MenuAdapter(Context context, int layoutResourceId, ArrayList<WebAddress> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        RegardingTypeHolder holder = null;
      
        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
          
            holder = new RegardingTypeHolder();
            holder.textName=(TextView)row.findViewById(R.id.link);
            row.setTag(holder);
        }
        else
        {
            holder = (RegardingTypeHolder)row.getTag();
        }
      
        WebAddress address = data.get(position);
        holder.textName.setText(address.getName());
        return row;
      
    }
  
    static class RegardingTypeHolder
    {
       
        TextView textName;
    }
}

 

create FacebookSlider.class

import java.util.ArrayList;
import java.util.Stack;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.android.adapter.MenuAdapter;
import com.android.facebookslider.FacebookSlideView;
import com.android.facebookslider.FacebookSlideView.SizeCallback;
import com.android.model.WebAddress;
import com.android.utilities.Config;
import com.example.facebookslider.R;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public class FacebookSlider extends Activity {
    FacebookSlideView scrollView;
    MenuAdapter menuAdapter;
    View menu;
    View app;
    Button btnSlide;
    static boolean menuOut = false;
    boolean isScan = false;
    Handler handler = new Handler();
    int btnWidth;
    ArrayList<WebAddress> address = new ArrayList<WebAddress>();
    WebView webView;
    ProgressDialog mProgress;
    boolean loadingFinished = true;
    boolean redirect = false;
    AlertDialog.Builder alert;
    boolean isWebHistory = false;

    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if( Build.VERSION.SDK_INT >= 9){
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

            StrictMode.setThreadPolicy(policy);
        }
       
        LayoutInflater inflater = LayoutInflater.from(this);
        scrollView = (FacebookSlideView) inflater.inflate(R.layout.screen_scroll_with_list_menu, null);
        setContentView(scrollView);

        final Stack stack=new Stack();
        menu = inflater.inflate(R.layout.horz_scroll_menu, null);
        app = inflater.inflate(R.layout.screen_facebook_slider, null);
        webView =(WebView) app.findViewById(R.id.webView);
        ViewGroup tabBar = (ViewGroup) app.findViewById(R.id.tabBar);
       
        address = Config.createAddress();
        menuAdapter = new MenuAdapter(this,R.layout.link, address);
        ListView listView = (ListView) menu.findViewById(R.id.list);
        //ViewUtils.initListView(this, listView, "Menu ", 8, android.R.layout.simple_list_item_1);
        listView.setAdapter(menuAdapter);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Context context = view.getContext();
                isWebHistory = true;
                webView.setVisibility(0);
                webView.getSettings().setJavaScriptEnabled(true);
                menuOut = true;
                scrollWebviw(scrollView, menu);
                // force web view to open inside application
                mProgress = ProgressDialog.show(FacebookSlider.this, "Loading", "Please wait for a moment...");
                webView.setWebViewClient(new MyWebViewClient());
                menuOut = false;
                stack.push(address.get(position).getName());
                Log.d("The contents of Stack is" , stack.toString());
                openURL(address.get(position).getUrl());
                webView.requestFocus(View.FOCUS_DOWN);
                webView.setOnTouchListener(new View.OnTouchListener() {
                       @Override
                    public boolean onTouch(View v, MotionEvent event) {
                           switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                        case MotionEvent.ACTION_UP:
                            if (!v.hasFocus()) {
                                v.requestFocus();
                            }
                            break;
                    }
                    return false;
                    }
                });
              
            }

        });
       
        btnSlide = (Button) tabBar.findViewById(R.id.BtnSlide);
      
        btnSlide.setOnClickListener(new ClickListenerForScrolling(scrollView, menu));

        final View[] children = new View[] { menu, app };

        // Scroll to app (view[1]) when layout finished.
        int scrollToViewIdx = 1;
       
        scrollView.initViews(children, scrollToViewIdx, new SizeCallbackForMenu(btnSlide));
    }
   
   

     /**
     * Helper for examples with a HSV that should be scrolled by a menu View's width.
     */
    static class ClickListenerForScrolling implements OnClickListener {
        FacebookSlideView scrollView;
        View menu;
        /**
         * Menu must NOT be out/shown to start with.
         */
        //boolean menuOut = false;

        public ClickListenerForScrolling(FacebookSlideView scrollView, View menu) {
            super();
            this.scrollView = scrollView;
            this.menu = menu;
        }

        @Override
        public void onClick(View v) {
            Context context = menu.getContext();
           
            int menuWidth = menu.getMeasuredWidth();

            // Ensure menu is visible
            menu.setVisibility(View.VISIBLE);

            if (!menuOut) {
                // Scroll to 0 to reveal menu
                Log.d("===slide==","Scroll to right");
                Log.d("===clicked==","clicked");
                int left =20;
                scrollView.smoothScrollTo(left, 0);
            } else {
                // Scroll to menuWidth so menu isn't on screen.
                Log.d("===slide==","Scroll to left");
                Log.d("===clicked==","clicked");
                int left = menuWidth;
                scrollView.smoothScrollTo(left, 0);
            }
            menuOut = !menuOut;
        }
    }

    /**
     * Helper that remembers the width of the 'slide' button, so that the 'slide' button remains in view, even when the menu is
     * showing.
     */
    static class SizeCallbackForMenu implements SizeCallback {
        int btnWidth;
        View btnSlide;

        public SizeCallbackForMenu(View btnSlide) {
            super();
            this.btnSlide = btnSlide;
        }

        @Override
        public void onGlobalLayout() {
            btnWidth = btnSlide.getMeasuredWidth();
            System.out.println("btnWidth=" + btnWidth);
        }

        @Override
        public void getViewSize(int idx, int w, int h, int[] dims) {
            dims[0] = w;
            dims[1] = h;
            final int menuIdx = 0;
            if (idx == menuIdx) {
                dims[0] = w - btnWidth;
            }
        }
    }
   
      
    private void openURL(String url) {
        webView.loadUrl(url);
    }
   
    private class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
         // TODO Auto-generated method stub
         super.onPageStarted(view, url, favicon);
         loadingFinished = false;
         menuOut = false;
         //mProgress.show();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
             if (!loadingFinished) {
                  redirect = true;
               }

            loadingFinished = false;
            view.loadUrl(url);
            return true;
        }
      
        // when finish loading page
        public void onPageFinished(WebView view, String url) {
            if(!redirect){
                  loadingFinished = true;
               }

               if(loadingFinished && !redirect){
                   if(null !=mProgress) {
                       if(mProgress.isShowing()) {
                            mProgress.dismiss();
                            menuOut = false;
                        }
                    }
                 
               } else{
                  redirect = false;
               }
        }
    }
   
    //scroll the page and open the webview
    private void scrollWebviw(FacebookSlideView scrollView, View menu) {
         Context context = menu.getContext();
        
         int menuWidth = menu.getMeasuredWidth();

         // Ensure menu is visible
         menu.setVisibility(View.VISIBLE);

         if (!menuOut) {
             // Scroll to 0 to reveal menu
             Log.d("===slide==","Scroll to right");
             int left = 0;
             scrollView.smoothScrollTo(left, 0);
         } else {
             // Scroll to menuWidth so menu isn't on screen.
             Log.d("===slide==","Scroll to left");
             int left = menuWidth;
             scrollView.smoothScrollTo(left, 0);
           
         }
         menuOut = false;
    }
   
     
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN){
            switch(keyCode)
            {
            case KeyEvent.KEYCODE_BACK:
                if(webView.canGoBack() == true){
                        webView.goBack();
                }else if(isWebHistory && webView.canGoBack() == false){
                    isWebHistory = false;
                    Intent menu = new Intent(FacebookSlider.this, FacebookSlider.class);
                    startActivity(menu);
                    webView.clearHistory();
                  
                }else{
                    webView.clearCache(true);
                    moveTaskToBack(true);
                    FacebookSlider.this.finish();
                }
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }
   
       
    @Override
    protected void onResume() {
        super.onResume();
      
    }
}


create FacebookSlideView.class

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.HorizontalScrollView;


public class FacebookSlideView extends HorizontalScrollView {
    public FacebookSlideView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public FacebookSlideView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public FacebookSlideView(Context context) {
        super(context);
        init(context);
    }

    void init(Context context) {
        // remove the fading as the HSV looks better without it
        setHorizontalFadingEdgeEnabled(false);
        setVerticalFadingEdgeEnabled(false);
    }

    public void initViews(View[] children, int scrollToViewIdx, SizeCallback sizeCallback) {
        // A ViewGroup MUST be the only child of the HSV
        ViewGroup parent = (ViewGroup) getChildAt(0);

        // Add all the children, but add them invisible so that the layouts are calculated, but you can't see the Views
        for (int i = 0; i < children.length; i++) {
            children[i].setVisibility(View.INVISIBLE);
            parent.addView(children[i]);
        }

        // Add a layout listener to this HSV
        // This listener is responsible for arranging the child views.
        OnGlobalLayoutListener listener = new MyOnGlobalLayoutListener(parent, children, scrollToViewIdx, sizeCallback);
        getViewTreeObserver().addOnGlobalLayoutListener(listener);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // Do not allow touch events.
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        // Do not allow touch events.
        return false;
    }

    class MyOnGlobalLayoutListener implements OnGlobalLayoutListener {
        ViewGroup parent;
        View[] children;
        int scrollToViewIdx;
        int scrollToViewPos = 0;
        SizeCallback sizeCallback;

        public MyOnGlobalLayoutListener(ViewGroup parent, View[] children, int scrollToViewIdx, SizeCallback sizeCallback) {
            this.parent = parent;
            this.children = children;
            this.scrollToViewIdx = scrollToViewIdx;
            this.sizeCallback = sizeCallback;
        }

        @Override
        public void onGlobalLayout() {
            // System.out.println("onGlobalLayout");

            final HorizontalScrollView me = FacebookSlideView.this;

            // The listener will remove itself as a layout listener to the HSV
            me.getViewTreeObserver().removeGlobalOnLayoutListener(this);

            // Allow the SizeCallback to 'see' the Views before we remove them and re-add them.
            // This lets the SizeCallback prepare View sizes, ahead of calls to SizeCallback.getViewSize().
            sizeCallback.onGlobalLayout();

            parent.removeViewsInLayout(0, children.length);

            final int w = me.getMeasuredWidth();
            final int h = me.getMeasuredHeight();

            // System.out.println("w=" + w + ", h=" + h);

            // Add each view in turn, and apply the width and height returned by the SizeCallback.
            int[] dims = new int[2];
            scrollToViewPos = 0;
            for (int i = 0; i < children.length; i++) {
                sizeCallback.getViewSize(i, w, h, dims);
                // System.out.println("addView w=" + dims[0] + ", h=" + dims[1]);
                children[i].setVisibility(View.VISIBLE);
                parent.addView(children[i], dims[0], dims[1]);
                if (i < scrollToViewIdx) {
                    scrollToViewPos += dims[0];
                }
            }

            // For some reason we need to post this action, rather than call immediately.
            // If we try immediately, it will not scroll.
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    me.scrollBy(scrollToViewPos, 0);
                }
            });
        }
    }

    public interface SizeCallback {
      
        public void onGlobalLayout();

        public void getViewSize(int idx, int w, int h, int[] dims);
    }
}








You can take images from here. 

And give permission in your manifest file <uses-permission android:name="android.permission.INTERNET" />



That's it enjoy coding.

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