Thursday 11 December 2014

Complete JSON parsing in Android Application for Beginners


JSONHandler.java

package com.rakesht.json;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

/**
 * Adds the ability to JSON Lib (in Android) to parse JSON data into Bean Class. It
 * is based on Android's (org.json.*)
 *
 * @author
 *
 */
public class JSONHandler {

    String TAG = "My App";
   



    /**
     * Parse a JSONObject and create instance of BeanClass. The JSONObject can internally contain
     * any kind of Objects and Arrays. The field names of BeanClass should exactly match as the JSON
     * property name.
     *
     * TODO:
     * 1. Support JSONArray as initial argument. Note: JSONArray can be
     * intermediate argument during the recursion process.
     * 2. Support primitive/custom Array. At present it supports only ArrayList
     * 3. Support custom data types which doesn't belong to -same Base Package-
     * 
     * @param jsonStr JSON String
     * @param beanClass Java Bean class
     * @param basePackage Base package name which includes all Bean classes
     * @return Instance of of the Bean Class with parsed value embedded.
     * @throws Exception
     */
    public Object parse(String jsonStr, Class beanClass, String basePackage) throws Exception
    {
        /*
         * This will be a recursive method
         * 1. Read all member variables of BeanClass
         * 2. Read values from JSON
         * 3. If it is an ArrayList, call parse() with its type class
         * 4. If it is a Custom Class, call parse() with its type class
         */
        Object obj = null;
        JSONObject jsonObj = new JSONObject(jsonStr);
       
        if(beanClass == null){
            p("Class instance is Null");
            return null;
        }
       
        p("Class Name: "+ beanClass.getName());
        p("Package: "+ beanClass.getPackage().getName());
        // Read Class member fields
        Field[] props = beanClass.getDeclaredFields();
       
        if(props == null || props.length == 0)
        {
            /*
             * This class has no fields
             */
//            p("Class "+ beanClass.getName() +" is empty");
            return null;
        }
       
        // Create instance of this Bean class
        obj = beanClass.newInstance();
        // Set value of each member variable of this object
        for(int i=0; i<props.length; i++)
        {
            String fieldName = props[i].getName();
            // Filter public and static fields
            if(props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC))
            {
                // Skip static fields
//                p("Modifier: "+ props[i].getModifiers());
//                p("Static Field: "+ fieldName +" ....Skip");
                continue;
            }
           
            // Date Type of Field
            Class type = props[i].getType();
            String typeName = type.getName();
           
            /*
             * If the type is not primitive- [int, long, java.lang.String, float, double] and ArrayList/List
             * Check for Custom type 
             */
            if(typeName.equals("int")) // int type
            {
//                p("Primitive Field: "+ fieldName + " Type: "+ typeName);
                // Handle Integer data
                // Get associated Set method- Need to mention Method Argument
                Class[] parms = {type};
                @SuppressWarnings("unchecked")
                Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                m.setAccessible(true);
               
                // Set value- JSONObject.getInt()
                try{
                    m.invoke(obj, jsonObj.getInt(fieldName));
                }catch(Exception ex){
//                    p("Error: "+ ex.toString());
                }
            }
            else if(typeName.equals("long"))
            {
//                p("Primitive Field: "+ fieldName + " Type: "+ typeName);
                // Handle Integer data
                // Get associated Set method- Need to mention Method Argument
                Class[] parms = {type};
                Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                m.setAccessible(true);
               
                // Set value- JSONObject.getLong()
                try{
                    m.invoke(obj, jsonObj.getLong(fieldName));
                }catch(Exception ex){
//                    p("Error: "+ ex.toString());
                }
            }
            else if(typeName.equals("java.lang.String"))
            {
//                p("Primitive Field: >>>"+ fieldName + " Type: "+ typeName);
                // Handle Integer data
                // Get associated Set method- Need to mention Method Argument
                Class[] parms = {type};
                Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                m.setAccessible(true);
               
                // Set value- JSONObject.getString()
                try{
                    m.invoke(obj, jsonObj.getString(fieldName));
                }catch(Exception ex){
//                    p("Error: "+ ex.toString());
                }
            }
            else if(typeName.equals("double"))
            {
//                p("Primitive Field: "+ fieldName + " Type: "+ typeName);
                // Handle Integer data
                // Get associated Set method- Need to mention Method Argument
                Class[] parms = {type};
                Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                m.setAccessible(true);
               
                // Set value- JSONObject.getDouble()
                try{
                    m.invoke(obj,  jsonObj.getDouble(fieldName));
                }catch(Exception ex){
//                    p("Error: "+ ex.toString());
                }
            }
            else if(type.getName().equals(List.class.getName()) ||
                    type.getName().equals(ArrayList.class.getName())){
                // ArrayList
                // Find out the Generic i.e. Class type of its content
//                p("ArrayList Field: "+ fieldName + " Type: "+ type.getName() +" field: "+ props[i].toGenericString());
                String generic = props[i].getGenericType().toString();
//                p("ArrayList Generic: "+ generic);
               
                if(generic.indexOf("<") != -1){
                    // extract generic from <>
                    String genericType = generic.substring(generic.lastIndexOf("<")+1, generic.lastIndexOf(">"));
                    if(genericType != null){
                        // Further refactor it
                        //showClassDesc(Class.forName(genericType), basePackage);
                        // It is a JSON Array- loop through the Array and create instances
//                        p("Generic Type: "+ genericType);
                        JSONArray array = null;
                        try{
                            array = jsonObj.getJSONArray(fieldName);
                        }catch(Exception ex){
//                            p("Error: "+ ex.toString());
                            array = null;
                        }
                        /*
                         * If it is of Primitive types, loop through the JSON Array and read tem into an
                         * ArrayList
                         */
                        if(array == null)
                            continue;
//                        p("JSON Array Size: "+ array.length());
                        ArrayList arrayList = new ArrayList();
                        for(int j=0; j<array.length(); j++)
                        {
                            arrayList.add(parse(array.getJSONObject(j).toString(), Class.forName(genericType), basePackage));
                        }
                       
                        // Set the value
                        Class[] parms = {type};
                        Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                        m.setAccessible(true);
                        m.invoke(obj,  arrayList);
                    }
                   
                }
                else{
                    // No generic defined
                    // ArrayList<Generic_Type>
                    generic = null;
                }
            }
            else if(typeName.startsWith(basePackage)){
                // Custom Class
                // Handle Custom class
                // Get associated Set method- Need to mention Method Argument
//                p("Custom class Field: "+ fieldName + " Type: "+ typeName);
                Class[] parms = {type};
                Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                m.setAccessible(true);
               
                // Set value- do a recursive Call to read values of this custom class
                try{
                    JSONObject customObj = jsonObj.getJSONObject(fieldName);
                    if(customObj != null)
                        m.invoke(obj, parse(customObj.toString(), type, basePackage));
                }catch(JSONException ex){
//                    p("Error: "+ ex.toString());
                    // TODO: set default value
                }
            }
            else{
                // Skip it
//                p("Skip, Field: "+ fieldName +" Type: "+ typeName +" SimpleTypeName: "+  type.getSimpleName());
            }
        }
        return obj;
    }
   
    /**
     * Generate Get/Set method of BeanClass fields
     * @param fieldName
     * @param type
     * @return
     */
    private String getBeanMethodName(String fieldName, int type){
        if(fieldName == null || fieldName == "")
            return "";
        String method_name = "";
        if(type == 0)
            method_name = "get";
        else
            method_name = "set";
        method_name += fieldName.substring(0, 1).toUpperCase();
       
        if(fieldName.length() == 1)// Field name is of 1 char
            return method_name;
       
        method_name += fieldName.substring(1);
        return method_name;
    }
   
    private void p(String msg){
        //System.out.println(msg);
//        Log.v(TAG, "# "+ msg);
    }
}

**********************************************************************************

package com.rakesht.json;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class MyHttpConnection {
   
    private HttpClient httpClient;
    private HttpPost httpPost;
    private HttpResponse httpResponse;
    private InputStream inputStream;
    private BufferedReader bufferedReader;
    private String returnData=null;
   
    public MyHttpConnection(){
       
    }
   
    public static String makeConnection(String urlString){
        String urlStr = urlString.replaceAll(" ", "%20").replaceAll("'", "%27");
        Log.d("System out", "Url==> "+ urlStr);
        URL url;
        HttpURLConnection connection;
        StringBuffer buffer = null;
       
        try {
            url = new URL(urlStr);
            connection = (HttpURLConnection)url.openConnection();
            buffer = new StringBuffer();
            InputStreamReader inputReader = new InputStreamReader(connection.getInputStream());
            BufferedReader buffReader = new BufferedReader(inputReader);
            String line = "";
            do {
                line = buffReader.readLine();
                if (line != null)
                    buffer.append(line);
            } while (line != null);
           
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        Log.d("System out", "Response==> "+ buffer.toString());
        return buffer.toString();
    }   
    public String excutePost(String url, String urlParameters)
      {
        URL url1;
        HttpURLConnection connection = null; 
        try {
          //Create connection
          url1 = new URL(url);
          connection = (HttpURLConnection)url1.openConnection();
          connection.setRequestMethod("POST");
          connection.setRequestProperty("Content-Type",
               "application/json");
               
          connection.setRequestProperty("Content-Length", "" +
                   Integer.toString(urlParameters.getBytes().length));
          connection.setRequestProperty("Content-Language", "en-US"); 
               
          connection.setUseCaches (false);
          connection.setDoInput(true);
          connection.setDoOutput(true);

          //Send request
          DataOutputStream wr = new DataOutputStream (
                      connection.getOutputStream ());
          wr.writeBytes (urlParameters);
          wr.flush ();
          wr.close ();

          //Get Response   
          InputStream is = connection.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          String line;
          StringBuffer response = new StringBuffer();
          while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
          }
          rd.close();
          return response.toString();

        } catch (Exception e) {

          e.printStackTrace();
          return null;

        } finally {

          if(connection != null) {
            connection.disconnect();
          }
        }
      }
    public String ParsedData(String GETURL, String Function){
       
        try{
            Log.d("System out", "Function in parsed Data "+Function);
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(GETURL);
            httpPost.setEntity(new StringEntity(Function));
            httpResponse = httpClient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
            StringBuffer buffer = new StringBuffer();
            do{
                line = bufferedReader.readLine();
                Log.d("System out", "line "+line);
                if(line!=null){
                    buffer.append(line);
                }
            }while(line!=null);
            returnData = buffer.toString();
            bufferedReader.close();
            buffer = null;
        }catch (Exception e) {
            // TODO: handle exception
            returnData = null;
            Log.d("System out", "Error in ParsedData "+e.getMessage());
        }
        return returnData;
    }
}

**********************************************************************************


package com.rakesht.json;

import java.io.Serializable;

@SuppressWarnings("serial")
public class JSONParserDataActivity implements Serializable {

    private String Id, Name,Description, Image,
            Country, Latitude, Longitude, price;
    private String Includes, Excludes, Name, Id, Image;
     private String Id,Id,Id,Image,ImageCaption,hpCreatedDate;
    private String rms;
    private String facilityId,facName,facDescription,facImage,status,dateadded,datemodified;

    public String getFacilityId() {
        return facilityId;
    }

    public void setFacilityId(String facilityId) {
        this.facilityId = facilityId;
    }

    public String getFacName() {
        return facName;
    }

    public void setFacName(String facName) {
        this.facName = facName;
    }

    public String getFacDescription() {
        return facDescription;
    }

    public void setFacDescription(String facDescription) {
        this.facDescription = facDescription;
    }

    public String getFacImage() {
        return facImage;
    }

    public void setFacImage(String facImage) {
        this.facImage = facImage;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDateadded() {
        return dateadded;
    }

    public void setDateadded(String dateadded) {
        this.dateadded = dateadded;
    }

    public String getDatemodified() {
        return datemodified;
    }

    public void setDatemodified(String datemodified) {
        this.datemodified = datemodified;
    }

    public void setId(String Id) {
        this.Id = Id;
    }

    public String getId() {
        return Id;
    }

    public void setName(String Name) {
        this.Name = Name;
    }

    public String getName() {
        return Name;
    }

    public void setDescription(String Description) {
        this.Description = Description;
    }

    public String getDescription() {
        return Description;
    }

    public void setImage(StringImage) {
        this.Image = Image;
    }

    public String getImage() {
        return Image;
    }

    public void setCountry(String Country) {
        this.Country = Country;
    }

    public String getCountry() {
        return Country;
    }

    public void setLatitude(String Latitude) {
        this.Latitude = Latitude;
    }

    public String getLatitude() {
        return Latitude;
    }

    public void setLongitude(String Longitude) {
        this.Longitude = Longitude;
    }

    public String getLongitude() {
        return Longitude;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getPrice() {
        return price;
    }

    public void setIncludes(String Includes) {
        this.Includes = Includes;
    }

    public String getIncludes() {
        return Includes;
    }

    public void setExcludes(String Excludes) {
        this.Excludes = hrExcludes;
    }

    public String getExcludes() {
        return Excludes;
    }

    public void setName(String Name) {
        this.Name = Name;
    }

    public String getName() {
        return Name;
    }
   
}

**********************************************************************************
SigninActivity.java

package com.rakesht;

import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.rakesht.json.MyHttpConnection;

public class SigninActivity extends Activity implements OnClickListener{
    Intent i;
    Button Btn_signin,Btn_signup;
    TextView Txtv_forgot_password,Txtv_auto_login;
    EditText Edt_signin_email,Edt_signin_password;
    ImageView Imgv_canceltext_email,Imgv_canceltext_pass;
    CheckBox chkbx_autologin;
    LinearLayout lay_offer;
    private String username,password;
    String response = "";
    private ProgressDialog progressDialog;
    private boolean flag_response = false;
    ScrollView sign_in;
    private Boolean b1 = true, b2 = true, b3 = true, b4 = true, b5 = true;
    private NumberFormat nf;
   
    public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
              "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
              "\\@" +
              "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
              "(" +
              "\\." +
              "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
              ")+"
          );
    private Pattern pattern;
      private Matcher matcher;
    private SharedPreferences settings;
    private Editor editor;
      private static final String PASSWORD_PATTERN =
          "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
     
     
     
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sign_in);
        init();
        settings = getSharedPreferences("My_Pref", 0);
        editor=settings.edit();
        username=settings.getString("uname", "");
        password=settings.getString("pass", "");
        Log.i("System out","User name---2 : "+username);
        Log.i("System out","Password----2 : "+password);
       
//        if(((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).isActive())
//        {
//            lay_offer.setVisibility(View.INVISIBLE);
//        }
//        else
//        {
//            lay_offer.setVisibility(View.VISIBLE);
//        }
       
         if (username=="" || password=="")
            {
              
            }
            else
            {
                Log.i("System out","User name---3 : "+username);
                Log.i("System out","Password----3 : "+password);
               
                Edt_signin_email.setText(username);
                Edt_signin_password.setText(password);
                chkbx_autologin.setChecked(true);
                chkbx_autologin.setButtonDrawable(R.drawable.checkbox_selected_login);
               
            }

        //this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
       
       
        settings = getSharedPreferences("My_Pref", 0);
        editor=settings.edit();
      
       
        chkbx_autologin.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
           
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if(isChecked)
                {
//                    chkbx_autologin.setBackgroundResource(R.drawable.checkbox_selected_login);
                    chkbx_autologin.setButtonDrawable(R.drawable.checkbox_selected_login);
                }
                else
                {
                    chkbx_autologin.setButtonDrawable(R.drawable.checkbox_login);
                }
               
            }
        });
       
       
        final View activityRootView = findViewById(R.id.activityRoot);
       

       
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
                if (heightDiff > 100)
                {
                    lay_offer.setVisibility(View.INVISIBLE);
                }
                else
                {
                    lay_offer.setVisibility(View.VISIBLE);
                }
             }
        });
       
       
    }
   
   
   
   
   
//    public interface OnKeyboardVisibilityListener {
//
//        void onVisibilityChanged(boolean visible);
//    }
//
//    public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
//        final View activityRootView = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
//        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
//
//            private boolean wasOpened;
//
//        private final Rect r = new Rect();
//
//            @Override
//            public void onGlobalLayout() {
//                activityRootView.getWindowVisibleDisplayFrame(r);
//
//                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
//                boolean isOpen = heightDiff > 100;
//                if (isOpen == wasOpened) {
//                    lay_offer.setVisibility(View.VISIBLE);
//                    return;
//                }
//
//                else
//                {
//                    lay_offer.setVisibility(View.INVISIBLE);
//                }
//                wasOpened = isOpen;
//                listener.onVisibilityChanged(isOpen);
//            }
//        });
//    }
   
   
    public void init(){
       
       
        Btn_signin=(Button)findViewById(R.id.btn_signin);
        Btn_signup=(Button)findViewById(R.id.btn_signup);
        Txtv_forgot_password=(TextView)findViewById(R.id.tv_forgot_password);
        Edt_signin_email=(EditText)findViewById(R.id.edt_signin_email);
        Edt_signin_password=(EditText)findViewById(R.id.edt__signin_password);
        chkbx_autologin=(CheckBox)findViewById(R.id.imgv_auto_login);
        Imgv_canceltext_email=(ImageView)findViewById(R.id.imgv_cancel_email);
        Imgv_canceltext_pass=(ImageView)findViewById(R.id.imgv_cancel_pass);
        Btn_signin.setOnClickListener(this);
        Btn_signup.setOnClickListener(this);
        Txtv_forgot_password.setOnClickListener(this);
        chkbx_autologin.setOnClickListener(this);
        Imgv_canceltext_email.setOnClickListener(this);
         Imgv_canceltext_pass.setOnClickListener(this);
         Edt_signin_email.setOnClickListener(this);
         Edt_signin_password.setOnClickListener(this);
         sign_in=(ScrollView)findViewById(R.id.sign_in);
         lay_offer=(LinearLayout)findViewById(R.id.lay_offer);
         Edt_signin_email.addTextChangedListener(new TextWatcher()
         {
                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b1) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_canceltext_email.setVisibility(View.GONE);
                        } else {
                            Imgv_canceltext_email.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

         Edt_signin_email.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b1 = false;
                        Imgv_canceltext_email.setVisibility(View.GONE);
                        String st = Edt_signin_email.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Edt_signin_email.setText(st);
                        }
                    } else {
                        b1 = true;
                        String st = Edt_signin_email.getText().toString();
                        if (st.equals("")) {
                            Imgv_canceltext_email.setVisibility(View.GONE);
                        } else {
                            Imgv_canceltext_email.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
       
       
         Edt_signin_password.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b2) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_canceltext_pass.setVisibility(View.GONE);
                        } else {
                            Imgv_canceltext_pass.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

         Edt_signin_password.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b2 = false;
                        Imgv_canceltext_pass.setVisibility(View.GONE);
                        String st = Edt_signin_password.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Edt_signin_password.setText(st);
                        }
                    } else {
                        b2 = true;
                        String st = Edt_signin_password.getText().toString();
                        if (st.equals("")) {
                            Imgv_canceltext_pass.setVisibility(View.GONE);
                        } else {
                            Imgv_canceltext_pass.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
       
       
       
    }
   
    public void callDialog() {
        progressDialog = ProgressDialog.show(SigninActivity.this, null, "Loading...");
        progressDialog.setCancelable(true);
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                    getData();
            }
        }).start();
    }
   
    public void getData() {

        String signinemail = Edt_signin_email.getText().toString();
        String signinpassword = Edt_signin_password.getText().toString();
       
        String url="http://100.101.130.111/rakesh/json.php?action=login&userEmail="+signinemail+"&userPass="+signinpassword;

        Log.i("System out","url : "+url);
        response = MyHttpConnection.makeConnection(url);
        Log.i("System out","Response : "+response);
       
        if(response != null)
        {
           
            flag_response = true;
        }else {
            flag_response = false;
        }
        handler.sendEmptyMessage(0);
    }
   
    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if (progressDialog != null) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (flag_response) {
                   
                    RegisterNLJson();
                }else {
                    Toast.makeText(getApplicationContext(), "No data!", Toast.LENGTH_SHORT).show();
                }
            }
        };
    };
   
   
    public void RegisterNLJson() {
        JSONArray jsonArray;
        JSONObject jsonObject;
       
        try {
        jsonArray = new JSONArray(response);
       
        jsonObject = jsonArray.getJSONObject(0);
        if(jsonObject.has("status"))
        {
            String status=jsonObject.getString("status");
            Toast.makeText(getApplicationContext(), status, Toast.LENGTH_SHORT).show();
        }   
        else
        {
            Toast.makeText(getApplicationContext(), " Successfully Login", Toast.LENGTH_SHORT).show();
            editor.putString("userid", jsonObject.getString("userId"));
            editor.putString("userFirstName", jsonObject.getString("userFirstName"));
            editor.putString("userLastName", jsonObject.getString("userLastName"));
            editor.putString("userPhone", jsonObject.getString("userPhone"));
            editor.putString("userEmail", jsonObject.getString("userEmail"));
            editor.putString("userPass", jsonObject.getString("userPass"));
            editor.putString("userAddress", jsonObject.getString("userAddress"));
            editor.putString("userCity", jsonObject.getString("userCity"));
            editor.putString("userState", jsonObject.getString("userState"));
            editor.putString("userZip", jsonObject.getString("userZip"));
            editor.putString("userCountry", jsonObject.getString("userCountry"));
            editor.commit();

            i=new Intent(this,itemActivity.class);
            startActivity(i);
            //SigninActivity.this.finish();
        }   
           
//        SigninActivity.this.finish();
       
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
       
    }
   
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
       
        String signinemail = Edt_signin_email.getText().toString();
        String signinpassword = Edt_signin_password.getText().toString();
       
        if(v==Btn_signin)
        {
            if(signinemail.equals("") || signinpassword.equals(""))
            {
                if (signinemail.equals(""))
                {
                    Toast.makeText(SigninActivity.this, "Please enter email id",    Toast.LENGTH_LONG).show();

                }
               
                /*else if (signinemail.length()>0)
                {
                    Imgv_canceltext_email.setVisibility(View.VISIBLE);

                }*/
                else if (signinpassword.equals("")||signinpassword.length()<6)
                {
                    Toast.makeText(SigninActivity.this, "Please enter password",Toast.LENGTH_LONG).show();

                }
               
                else if (signinpassword.length()<6)
                {
                    Toast.makeText(SigninActivity.this, "Please enter password with minimum 6 character",Toast.LENGTH_LONG).show();

                }
               
               
            }
            else if (!checkEmail(signinemail))
            {
                Toast.makeText(SigninActivity.this, "Please enter valid email id",Toast.LENGTH_LONG).show();
            }
           
            /*else if(v==Edt_signin_email)
            {
                Imgv_canceltext_email.setVisibility(View.VISIBLE);
            }
            else if(v==Edt_signin_password)
            {
                Imgv_canceltext_pass.setVisibility(View.VISIBLE);
            }*/
           
            else
            {
                if(chkbx_autologin.isChecked())
                {
                    editor.putBoolean("remember", true);
                    editor.putString("username", signinemail);
                    editor.putString("password", signinpassword);
                    editor.putString("uname", signinemail);
                    editor.putString("pass", signinpassword);
                    editor.commit();
                }
               
                if(chkbx_autologin.isChecked()==false)
                {
                    editor.remove("remember");
                    editor.remove("username");
                    editor.remove("password");
                    editor.remove("uname");
                    editor.remove("pass");
                    editor.commit();
                }
                callDialog();
            }
           
           
        }
       
       
        else if(v==Imgv_canceltext_email)
        {
            Edt_signin_email.setText("");
        }
       
        else if(v==Imgv_canceltext_pass)
        {
            Edt_signin_password.setText("");
        }
       
        /*else if(v==chkbx_autologin)
        {
            if(chkbx_autologin.isChecked())
            {
                    chkbx_autologin.setButtonDrawable(R.drawable.checkbox_selected_login);
            }
            else
            {
                chkbx_autologin.setButtonDrawable(R.drawable.checkbox_login);
            }
        }*/
        else if(v==Btn_signup)
        {
            i=new Intent(this,SignupActivity.class);
            startActivity(i);
            //SigninActivity.this.finish();
        }
        else if(v==Txtv_forgot_password)
        {
            i=new Intent(this,ForgotPasswordActivity.class);
            startActivity(i);
            //SigninActivity.this.finish();
        }
       
       
       
    }

   
   
   
   
   
   
    private boolean checkEmail(String email) {
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }
   
     public SigninActivity()
     {
          pattern = Pattern.compile(PASSWORD_PATTERN);
      }
      public boolean validate(String signinpassword)
      {
          matcher = pattern.matcher(signinpassword);
          return matcher.matches();
      }

   
     /*@Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                // Finish activity on back button
//                this.finish();
                overridePendingTransition(R.anim.slide_in_left,
                        R.anim.slide_out_right);
            }
            return super.onKeyDown(keyCode, event);
        }
    */     
     
}

**********************************************************************************







SignupActivity.java



package com.r;akesht

import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.rakesht.json.MyHttpConnection;

public class SignupActivity extends Activity implements OnClickListener{
    Intent i;
    Button btn_signup_submit,btn_signup_cancel;
    ImageView Imgv_txtclear_fname,Imgv_txtclear_lname,Imgv_txtclear_email,Imgv_txtclear_phone,
    Imgv_txtclear_pass,Imgv_txtclear_confpass;
    TextView Tv_signup_back, Tv_signup_header;
    EditText Tv_first_name,Tv_last_name,Tv_phone,Tv_email,Tv_password,Tv_confirm_password;
    String response = "",firstname,lastname,email,phone,password,confirmpassword,mid;
    private ProgressDialog progressDialog;
    private boolean flag_response = false, b1 = true, b2 = true, b3 = true, b4 = true, b5 = true,b6=true;
   
//    Boolean update = false;
//    DBAdapter db;
    ArrayList<HashMap<String, String>> userdetail;
    ArrayAdapter ayArrayAdapter;
    String phonenoStr = "^[+][0-9]{10,13}$";
//     AlertDialog.Builder builder = new AlertDialog.Builder(this);
     public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
              "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
              "\\@" +
              "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
              "(" +
              "\\." +
              "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
              ")+"
          );
   
     private Pattern pattern;
      private Matcher matcher;
    private SharedPreferences settings;
    private Editor editor;
      private static final String PASSWORD_PATTERN =
//         "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
      "((?=.*[@#$%]).{6,20})";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
       setContentView(R.layout.sign_up);
      
       //this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
       init();
      
       settings = getSharedPreferences("My_Pref", 0);
        editor=settings.edit();
      
      
    }

    public void  init(){
       
        btn_signup_submit=(Button)findViewById(R.id.btn_submit);
           btn_signup_cancel=(Button)findViewById(R.id.btn_cancel);
//           Tv_signup_header=(TextView)findViewById(R.id.txtheaderResTitle);
          
           Tv_first_name=(EditText)findViewById(R.id.edt_signup_firstname);
           Tv_last_name=(EditText)findViewById(R.id.edt_signup_lastname);
           Tv_phone=(EditText)findViewById(R.id.edt_signup_phone);
           Tv_email=(EditText)findViewById(R.id.edt_signup_email);
           Tv_password=(EditText)findViewById(R.id.edt_signup_password);
           Tv_confirm_password=(EditText)findViewById(R.id.edt_signup_confirm_pass);
           Imgv_txtclear_fname=(ImageView)findViewById(R.id.imgv_cancel_fname);
           Imgv_txtclear_lname=(ImageView)findViewById(R.id.imgv_cancel_lname);
           Imgv_txtclear_email=(ImageView)findViewById(R.id.imgv_cancel_email);
           Imgv_txtclear_phone=(ImageView)findViewById(R.id.imgv_cancel_phone);
           Imgv_txtclear_pass=(ImageView)findViewById(R.id.imgv_cancel_pass);
           Imgv_txtclear_confpass=(ImageView)findViewById(R.id.imgv_cancel_confpass);
          
//           Tv_signup_header.setText("Sign Up");
//           Tv_signup_back=(TextView)findViewById(R.id.back);
//           Tv_signup_back.setVisibility(View.GONE);
           btn_signup_submit.setOnClickListener(this);
           btn_signup_cancel.setOnClickListener(this);
           Imgv_txtclear_fname.setOnClickListener(this);
           Imgv_txtclear_lname.setOnClickListener(this);
           Imgv_txtclear_email.setOnClickListener(this);
           Imgv_txtclear_phone.setOnClickListener(this);
           Imgv_txtclear_pass.setOnClickListener(this);
           Imgv_txtclear_confpass.setOnClickListener(this);
         
          
           Tv_first_name.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b1) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_txtclear_fname.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_fname.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

           Tv_first_name.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b1 = false;
                        Imgv_txtclear_fname.setVisibility(View.GONE);
                        String st = Tv_first_name.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Tv_first_name.setText(st);
                        }
                    } else {
                        b1 = true;
                        String st = Tv_first_name.getText().toString();
                        if (st.equals("")) {
                            Imgv_txtclear_fname.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_fname.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
           
           Tv_last_name.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b2) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_txtclear_lname.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_lname.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

           Tv_last_name.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b2 = false;
                        Imgv_txtclear_lname.setVisibility(View.GONE);
                        String st = Tv_last_name.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Tv_last_name.setText(st);
                        }
                    } else {
                        b2 = true;
                        String st = Tv_last_name.getText().toString();
                        if (st.equals("")) {
                            Imgv_txtclear_lname.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_lname.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
           Tv_phone.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b3) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_txtclear_phone.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_phone.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

           Tv_phone.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b3 = false;
                        Imgv_txtclear_phone.setVisibility(View.GONE);
                        String st = Tv_phone.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Tv_phone.setText(st);
                        }
                    } else {
                        b3 = true;
                        String st = Tv_phone.getText().toString();
                        if (st.equals("")) {
                            Imgv_txtclear_phone.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_phone.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
           Tv_email.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b4) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_txtclear_email.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_email.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

           Tv_email.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b4 = false;
                        Imgv_txtclear_email.setVisibility(View.GONE);
                        String st = Tv_email.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Tv_email.setText(st);
                        }
                    } else {
                        b4 = true;
                        String st = Tv_email.getText().toString();
                        if (st.equals("")) {
                            Imgv_txtclear_email.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_email.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
           Tv_password.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b5) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_txtclear_pass.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_pass.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

           Tv_password.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b5 = false;
                        Imgv_txtclear_pass.setVisibility(View.GONE);
                        String st = Tv_password.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Tv_password.setText(st);
                        }
                    } else {
                        b5 = true;
                        String st = Tv_password.getText().toString();
                        if (st.equals("")) {
                            Imgv_txtclear_pass.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_pass.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
           Tv_confirm_password.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b6) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_txtclear_confpass.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_confpass.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

           Tv_confirm_password.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b6 = false;
                        Imgv_txtclear_confpass.setVisibility(View.GONE);
                        String st = Tv_confirm_password.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Tv_confirm_password.setText(st);
                        }
                    } else {
                        b6 = true;
                        String st = Tv_confirm_password.getText().toString();
                        if (st.equals("")) {
                            Imgv_txtclear_confpass.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_confpass.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
          
          
    }
   
   
    public void callDialog() {
        progressDialog = ProgressDialog.show(SignupActivity.this, null, "Loading...");
        progressDialog.setCancelable(true);
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                    getData();
            }
        }).start();
    }
   
    public void getData() {

        firstname=Tv_first_name.getText().toString();
        lastname=Tv_last_name.getText().toString();
        email=Tv_email.getText().toString();
        phone=Tv_phone.getText().toString();
        password=Tv_password.getText().toString();
       
//        String url="http://100.101.130.200/rakesht/json.php?action=Registernewsletter&json=[{\"nlSubscriberFN\":\""+firstname+"\",\"nlSubscriberLN\":\""+lastname+"\",\"nlSubscriberEmail\":\""+email+"\",\"age\":\""+age+"\",\"country\":\""+country+"\",\"sex\":\""+gender+"\"}]";
        String url="http://100.101.130.200/rakesht/json.php?action=insertusers&json=[{\"userFirstName\":\""+firstname+"\",\"userLastName\":\""+lastname+"\",\"userPhone\":\""+phone+"\",\"userEmail\":\""+email+"\",\"userPass\":\""+password+"\"}]";
//        String url="http://100.101.130.200/rakesht/json.php?action=insertusers&json=[{%22userFirstName%22:%22a%22,%22userLastName%22:%22b%22,%22userPhone%22:%229876543214%22,%22userEmail%22:%22abc@gmail.com%22,%22userPass%22:%22abc%22}]";
       

        response =MyHttpConnection.makeConnection(url);
        Log.i("System out","Response : "+response);

        if(response != null){
            flag_response = true;
        }else {
            flag_response = false;
        }
        handler.sendEmptyMessage(0);
    }
   
    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if (progressDialog != null) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (flag_response) {
                   
                    RegisterNLJson();
                }else {
                    Toast.makeText(getApplicationContext(), "No data!", Toast.LENGTH_SHORT).show();
                }
            }
        };
    };
   
   
    public void RegisterNLJson() {
        JSONArray jsonArray;
        JSONObject jsonObject;
       
        try {
        jsonArray = new JSONArray(response);
       
        jsonObject = jsonArray.getJSONObject(0);
        Log.v("System out","Response : in fun"+jsonObject);
        String status=jsonObject.getString("userId");
       
        if(status!=null)
        {
        Log.v("System out","Response : in status"+status);
        Toast.makeText(getApplicationContext(), "Signup successfully.", Toast.LENGTH_SHORT).show();
       
        editor.putString("uname", Tv_email.getText().toString());
        editor.putString("pass", Tv_password.getText().toString());
        editor.commit();
       
        i=new Intent(this,SigninActivity.class);
        startActivity(i);
//        SignupActivity.this.finish();
        }else{
            Toast.makeText(getApplicationContext(), status, Toast.LENGTH_SHORT).show();
        }
           
       
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }
   
   
   
   
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
       
         String firstname=Tv_first_name.getText().toString();
            String lastname=Tv_last_name.getText().toString();
            String phone=Tv_phone.getText().toString();
            String email=Tv_email.getText().toString();
            String password=Tv_password.getText().toString();
            String confirmpassword=Tv_confirm_password.getText().toString();
           
           
             if(v==btn_signup_cancel){
//                SignupActivity.this.finish();
                i=new Intent(this,SigninActivity.class);
                startActivity(i);
            }
           
             else if(v==Imgv_txtclear_fname){
                 Tv_first_name.setText("");
               
             }
             else if(v==Imgv_txtclear_lname){
                 Tv_last_name.setText("");
             }
             else if(v==Imgv_txtclear_email){
               
                 Tv_email.setText("");
               
             }
             else if(v==Imgv_txtclear_phone){
                 Tv_phone.setText("");
             }
             else if(v==Imgv_txtclear_pass){
                 Tv_password.setText("");
             }
             else if(v==Imgv_txtclear_confpass){
                 Tv_confirm_password.setText("");
             }
       
             else    if(v==btn_signup_submit){
           
           
            if (firstname.equals("") || lastname.equals("")
                    || phone.equals("")||email.equals("")|| password.equals("")|| confirmpassword.equals("")) {
                if (firstname.equals("")) {
                    Toast.makeText(SignupActivity.this, "Please provide first name",
                            Toast.LENGTH_LONG).show();

                }
                else if (lastname.equals("")) {
                    Toast.makeText(SignupActivity.this, "Please provide last name",
                            Toast.LENGTH_LONG).show();

                }
               
               
                else if (email.equals("")) {
                    Toast.makeText(SignupActivity.this, "Please provide email id",
                            Toast.LENGTH_LONG).show();

                }
                /*else if (!checkEmail(email)) {
                    Toast.makeText(SignupActivity.this, "Please provide valid email id",
                            Toast.LENGTH_LONG).show();
                }*/
               
               
               
                else if (phone.equals("")) {
                    Toast.makeText(SignupActivity.this, "Please provide phone no",
                            Toast.LENGTH_LONG).show();

                }
               
                /*else if(phone.matches(phonenoStr)==false  ) {
                            Toast.makeText(SignupActivity.this," Please provide phone no",Toast.LENGTH_SHORT).show();
                           // am_checked=0;
                        }*/
               
                /*else if(phone.length()<10||phone.length()>15) {
                    Toast.makeText(SignupActivity.this," Please provide valid phone no",Toast.LENGTH_SHORT).show();
                   // am_checked=0;
                }*/
               
                else if (password.equals("")) {
                    Toast.makeText(SignupActivity.this, "Please provide password",
                            Toast.LENGTH_LONG).show();

                }
                else if (password.length()<6) {
                    Toast.makeText(SignupActivity.this, "Please provide password with minimum 6 character",
                            Toast.LENGTH_LONG).show();

                }
               
                else if (confirmpassword.equals("")) {
                    Toast.makeText(SignupActivity.this, "Please provide confirm password",
                            Toast.LENGTH_LONG).show();

                }
               
               
               
            }   
               
           
             else if (!checkEmail(email)) {
                    Toast.makeText(SignupActivity.this, "Please provide valid email id",
                            Toast.LENGTH_LONG).show();
                }
           
           
            else if(phone.length()<12||phone.length()>15) {
                Toast.makeText(SignupActivity.this," Please provide valid phone no",Toast.LENGTH_SHORT).show();
               // am_checked=0;
            }
                   
           
             else if (password.length()<6) {
                    Toast.makeText(SignupActivity.this, "Please provide password with minimum 6 character",
                            Toast.LENGTH_LONG).show();

                }
           
             else if (!confirmpassword .equals(password)) {
               
                 Toast.makeText(SignupActivity.this, "Password and Confirm password should be match",
                            Toast.LENGTH_LONG).show();
               
                /* AlertDialog alertDialog = new AlertDialog.Builder(SignupActivity.this).create();
                    alertDialog.setTitle("oops!");
                    alertDialog.setMessage("Passwords do not match");
                    alertDialog.setButton("Ok",
                    new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                              //dismiss the dialog 
                            }
                        });
                    alertDialog.show();*/

                }
           
           
           
           
             else{
               
                 callDialog();   
   
               
             }
                       
                   
        }
           
       
    }
   
    private boolean checkEmail(String email) {
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }

    public SignupActivity(){
          pattern = Pattern.compile(PASSWORD_PATTERN);
      }
      public boolean validate(String password){
           
          matcher = pattern.matcher(password);
          return matcher.matches();

      }

}

**********************************************************************************

















package com.rakesht;


import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.rakesht.JSONHandler;
import com.rakesht.json.JSONParserDataActivity;
import com.rakesht.json.MyHttpConnection;

public class ItemActivity extends Activity implements OnClickListener{
    TextView Tv_item_back,Tv_item_header;
    ListView Lv_item;
    ImageLoader imageDownloadNewList;
    String response = "",  getSearch;
    Editor editor;

    private MobileArrayAdapter listAdapter;
    SharedPreferences preferences;
    private ProgressDialog progressDialog;
    private boolean flag_response = false;
    private int selectedOption;
    ImageView Imgv_selected;
    private final ArrayList<JSONParserDataActivity> itemArrayList = new ArrayList<JSONParserDataActivity>();
   
     
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
          setContentView(R.layout.item);
   
    init();
    Imgv_selected=(ImageView)findViewById(Footer.ABOUT_ID);
    Imgv_selected.setImageResource(R.drawable.icon_about_selected);
    }
   
    public void init(){
       
        Lv_item=(ListView)findViewById(R.id.item_listv);
        imageDownloadNewList = new ImageLoader(this);
        preferences = getSharedPreferences("My_Pref", 0);
        editor=preferences.edit();
        selectedOption = getIntent().getIntExtra("from", selectedOption);
        getSearch="http://100.101.130.200/rakesht/json.php?action=getitem&page=1";
        callDialog();
    }
   
    public void callDialog() {
        progressDialog = ProgressDialog.show(itemActivity.this, null, "Loading...");
        progressDialog.setCancelable(true);
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                getData();
            }
        }).start();
    }

    public void getData() {

        response = MyHttpConnection.makeConnection(getSearch);
       
        Log.i("System out","Response : "+response);

        if(response != null){
            flag_response = true;
        }else {
            flag_response = false;
        }
        handler.sendEmptyMessage(0);
    }

    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if (progressDialog != null) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (flag_response) {
                    setData();
                }else {
                    Toast.makeText(getApplicationContext(), "No data!", Toast.LENGTH_SHORT).show();
                }
            }
        };
    };

    public void setData() {
        try {
            JSONArray jsonArray;
            JSONObject jsonObject;

            jsonArray = new JSONArray(response);
            for (int i = 0; i < jsonArray.length(); i++) {
                jsonObject = jsonArray.getJSONObject(i);
                itemArrayList.add((JSONParserDataActivity) new JSONHandler().parse(
                        jsonObject.toString(), JSONParserDataActivity.class,
                        "com.rakesh.json"));
            }

            Log.i("System out", "itemname : " + itemArrayList.size()+"\n"+itemArrayList.get(0).getitemName());

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "No item found!", Toast.LENGTH_SHORT).show();
            //itemActivity.this.finish();
        }

        if (itemArrayList.isEmpty()) {
            //Toast.makeText(getApplicationContext(), "No record found!", Toast.LENGTH_SHORT).show();
            //itemActivity.this.finish();
        }else {
            Lv_item=(ListView)findViewById(R.id.item_listv);
            Lv_item.setDivider(getResources().getDrawable(R.drawable.line));
            Lv_item.setCacheColorHint(Color.TRANSPARENT);
            Lv_item.setFocusable(true);
            listAdapter=new MobileArrayAdapter(this, itemArrayList);

           Lv_item.setAdapter( listAdapter );

           Lv_item.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?>parent, View view,int position, long id){

                         editor.putString("itemID", itemArrayList.get(position).getItemId());
                        editor.putString("itemname", itemArrayList.get(position).getItemName());
                        editor.putString("price", itemArrayList.get(position).getPrice());
//                        editor.putString("getItemDescription", itemArrayList.get(position).getItemDescription());
                        editor.commit();
                        Intent i=new Intent(getApplicationContext(),ItemDetailActivity.class);
                        startActivity(i);
                        //itemActivity.this.finish();
                       
                }
            });
        }
    }

   
    public class MobileArrayAdapter extends ArrayAdapter<JSONParserDataActivity> {
        private final Context context;
       

        public MobileArrayAdapter(Context context,ArrayList<JSONParserDataActivity> itemArrayList) {
            super(context, R.layout.item_list_item, itemArrayList);
            this.context = context;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View rowView = inflater.inflate(R.layout.item_list_item, parent,
                    false);
            TextView tvitemname = (TextView) rowView.findViewById(R.id.txt_item_name);
                   
            TextView tvitemdescription = (TextView) rowView.findViewById(R.id.txt_item_description);
            TextView tvitem = (TextView) rowView.findViewById(R.id.tv_item_rent);
            ImageView imgvitemimage=(ImageView)rowView.findViewById(R.id.imageView_item);   
           
            try {
               
                imageDownloadNewList.DisplayImage(getString(R.string.url_image_item)+
                        itemArrayList.get(position)
                        .getItemImage()
                        .replace(" ", "%20"),imgvitemlimage);
                tvitemname.setText(itemArrayList.get(position).getItemName());
                tvitemdescription.setText(itemArrayList.get(position).getItemDescription());
                tvitem.setText(itemArrayList.get(position).getPrice());
               
               
            } catch (Exception e)
            {
                // TODO: handle exception
                e.printStackTrace();
                //Toast.makeText(getApplicationContext(), "No record found!", Toast.LENGTH_SHORT).show();
                //itemActivity.this.finish();
            }
           
           

            return rowView;
        }
    }







    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
       
    }
   
   
   

}



JSONHandler.java

package com.rakesht.json;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

/**
 * Adds the ability to JSON Lib (in Android) to parse JSON data into Bean Class. It
 * is based on Android's (org.json.*)
 *
 * @author
 *
 */
public class JSONHandler {

    String TAG = "My App";
   

    /**
     * Parse a JSONObject and create instance of BeanClass. The JSONObject can internally contain
     * any kind of Objects and Arrays. The field names of BeanClass should exactly match as the JSON
     * property name.
     *
     * TODO:
     * 1. Support JSONArray as initial argument. Note: JSONArray can be
     * intermediate argument during the recursion process.
     * 2. Support primitive/custom Array. At present it supports only ArrayList
     * 3. Support custom data types which doesn't belong to -same Base Package-
     * 
     * @param jsonStr JSON String
     * @param beanClass Java Bean class
     * @param basePackage Base package name which includes all Bean classes
     * @return Instance of of the Bean Class with parsed value embedded.
     * @throws Exception
     */
    public Object parse(String jsonStr, Class beanClass, String basePackage) throws Exception
    {
        /*
         * This will be a recursive method
         * 1. Read all member variables of BeanClass
         * 2. Read values from JSON
         * 3. If it is an ArrayList, call parse() with its type class
         * 4. If it is a Custom Class, call parse() with its type class
         */
        Object obj = null;
        JSONObject jsonObj = new JSONObject(jsonStr);
       
        if(beanClass == null){
            p("Class instance is Null");
            return null;
        }
       
        p("Class Name: "+ beanClass.getName());
        p("Package: "+ beanClass.getPackage().getName());
        // Read Class member fields
        Field[] props = beanClass.getDeclaredFields();
       
        if(props == null || props.length == 0)
        {
            /*
             * This class has no fields
             */
//            p("Class "+ beanClass.getName() +" is empty");
            return null;
        }
       
        // Create instance of this Bean class
        obj = beanClass.newInstance();
        // Set value of each member variable of this object
        for(int i=0; i<props.length; i++)
        {
            String fieldName = props[i].getName();
            // Filter public and static fields
            if(props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC))
            {
                // Skip static fields
//                p("Modifier: "+ props[i].getModifiers());
//                p("Static Field: "+ fieldName +" ....Skip");
                continue;
            }
           
            // Date Type of Field
            Class type = props[i].getType();
            String typeName = type.getName();
           
            /*
             * If the type is not primitive- [int, long, java.lang.String, float, double] and ArrayList/List
             * Check for Custom type 
             */
            if(typeName.equals("int")) // int type
            {
//                p("Primitive Field: "+ fieldName + " Type: "+ typeName);
                // Handle Integer data
                // Get associated Set method- Need to mention Method Argument
                Class[] parms = {type};
                @SuppressWarnings("unchecked")
                Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                m.setAccessible(true);
               
                // Set value- JSONObject.getInt()
                try{
                    m.invoke(obj, jsonObj.getInt(fieldName));
                }catch(Exception ex){
//                    p("Error: "+ ex.toString());
                }
            }
            else if(typeName.equals("long"))
            {
//                p("Primitive Field: "+ fieldName + " Type: "+ typeName);
                // Handle Integer data
                // Get associated Set method- Need to mention Method Argument
                Class[] parms = {type};
                Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                m.setAccessible(true);
               
                // Set value- JSONObject.getLong()
                try{
                    m.invoke(obj, jsonObj.getLong(fieldName));
                }catch(Exception ex){
//                    p("Error: "+ ex.toString());
                }
            }
            else if(typeName.equals("java.lang.String"))
            {
//                p("Primitive Field: >>>"+ fieldName + " Type: "+ typeName);
                // Handle Integer data
                // Get associated Set method- Need to mention Method Argument
                Class[] parms = {type};
                Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                m.setAccessible(true);
               
                // Set value- JSONObject.getString()
                try{
                    m.invoke(obj, jsonObj.getString(fieldName));
                }catch(Exception ex){
//                    p("Error: "+ ex.toString());
                }
            }
            else if(typeName.equals("double"))
            {
//                p("Primitive Field: "+ fieldName + " Type: "+ typeName);
                // Handle Integer data
                // Get associated Set method- Need to mention Method Argument
                Class[] parms = {type};
                Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                m.setAccessible(true);
               
                // Set value- JSONObject.getDouble()
                try{
                    m.invoke(obj,  jsonObj.getDouble(fieldName));
                }catch(Exception ex){
//                    p("Error: "+ ex.toString());
                }
            }
            else if(type.getName().equals(List.class.getName()) ||
                    type.getName().equals(ArrayList.class.getName())){
                // ArrayList
                // Find out the Generic i.e. Class type of its content
//                p("ArrayList Field: "+ fieldName + " Type: "+ type.getName() +" field: "+ props[i].toGenericString());
                String generic = props[i].getGenericType().toString();
//                p("ArrayList Generic: "+ generic);
               
                if(generic.indexOf("<") != -1){
                    // extract generic from <>
                    String genericType = generic.substring(generic.lastIndexOf("<")+1, generic.lastIndexOf(">"));
                    if(genericType != null){
                        // Further refactor it
                        //showClassDesc(Class.forName(genericType), basePackage);
                        // It is a JSON Array- loop through the Array and create instances
//                        p("Generic Type: "+ genericType);
                        JSONArray array = null;
                        try{
                            array = jsonObj.getJSONArray(fieldName);
                        }catch(Exception ex){
//                            p("Error: "+ ex.toString());
                            array = null;
                        }
                        /*
                         * If it is of Primitive types, loop through the JSON Array and read tem into an
                         * ArrayList
                         */
                        if(array == null)
                            continue;
//                        p("JSON Array Size: "+ array.length());
                        ArrayList arrayList = new ArrayList();
                        for(int j=0; j<array.length(); j++)
                        {
                            arrayList.add(parse(array.getJSONObject(j).toString(), Class.forName(genericType), basePackage));
                        }
                       
                        // Set the value
                        Class[] parms = {type};
                        Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                        m.setAccessible(true);
                        m.invoke(obj,  arrayList);
                    }
                   
                }
                else{
                    // No generic defined
                    // ArrayList<Generic_Type>
                    generic = null;
                }
            }
            else if(typeName.startsWith(basePackage)){
                // Custom Class
                // Handle Custom class
                // Get associated Set method- Need to mention Method Argument
//                p("Custom class Field: "+ fieldName + " Type: "+ typeName);
                Class[] parms = {type};
                Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                m.setAccessible(true);
               
                // Set value- do a recursive Call to read values of this custom class
                try{
                    JSONObject customObj = jsonObj.getJSONObject(fieldName);
                    if(customObj != null)
                        m.invoke(obj, parse(customObj.toString(), type, basePackage));
                }catch(JSONException ex){
//                    p("Error: "+ ex.toString());
                    // TODO: set default value
                }
            }
            else{
                // Skip it
//                p("Skip, Field: "+ fieldName +" Type: "+ typeName +" SimpleTypeName: "+  type.getSimpleName());
            }
        }
        return obj;
    }
   
    /**
     * Generate Get/Set method of BeanClass fields
     * @param fieldName
     * @param type
     * @return
     */
    private String getBeanMethodName(String fieldName, int type){
        if(fieldName == null || fieldName == "")
            return "";
        String method_name = "";
        if(type == 0)
            method_name = "get";
        else
            method_name = "set";
        method_name += fieldName.substring(0, 1).toUpperCase();
       
        if(fieldName.length() == 1)// Field name is of 1 char
            return method_name;
       
        method_name += fieldName.substring(1);
        return method_name;
    }
   
    private void p(String msg){
        //System.out.println(msg);
//        Log.v(TAG, "# "+ msg);
    }
}

**********************************************************************************

package com.rakesht.json;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class MyHttpConnection {
   
    private HttpClient httpClient;
    private HttpPost httpPost;
    private HttpResponse httpResponse;
    private InputStream inputStream;
    private BufferedReader bufferedReader;
    private String returnData=null;
   
    public MyHttpConnection(){
       
    }
   
    public static String makeConnection(String urlString){
        String urlStr = urlString.replaceAll(" ", "%20").replaceAll("'", "%27");
        Log.d("System out", "Url==> "+ urlStr);
        URL url;
        HttpURLConnection connection;
        StringBuffer buffer = null;
       
        try {
            url = new URL(urlStr);
            connection = (HttpURLConnection)url.openConnection();
            buffer = new StringBuffer();
            InputStreamReader inputReader = new InputStreamReader(connection.getInputStream());
            BufferedReader buffReader = new BufferedReader(inputReader);
            String line = "";
            do {
                line = buffReader.readLine();
                if (line != null)
                    buffer.append(line);
            } while (line != null);
           
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        Log.d("System out", "Response==> "+ buffer.toString());
        return buffer.toString();
    }   
    public String excutePost(String url, String urlParameters)
      {
        URL url1;
        HttpURLConnection connection = null; 
        try {
          //Create connection
          url1 = new URL(url);
          connection = (HttpURLConnection)url1.openConnection();
          connection.setRequestMethod("POST");
          connection.setRequestProperty("Content-Type",
               "application/json");
               
          connection.setRequestProperty("Content-Length", "" +
                   Integer.toString(urlParameters.getBytes().length));
          connection.setRequestProperty("Content-Language", "en-US"); 
               
          connection.setUseCaches (false);
          connection.setDoInput(true);
          connection.setDoOutput(true);

          //Send request
          DataOutputStream wr = new DataOutputStream (
                      connection.getOutputStream ());
          wr.writeBytes (urlParameters);
          wr.flush ();
          wr.close ();

          //Get Response   
          InputStream is = connection.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          String line;
          StringBuffer response = new StringBuffer();
          while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
          }
          rd.close();
          return response.toString();

        } catch (Exception e) {

          e.printStackTrace();
          return null;

        } finally {

          if(connection != null) {
            connection.disconnect();
          }
        }
      }
    public String ParsedData(String GETURL, String Function){
       
        try{
            Log.d("System out", "Function in parsed Data "+Function);
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(GETURL);
            httpPost.setEntity(new StringEntity(Function));
            httpResponse = httpClient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
            StringBuffer buffer = new StringBuffer();
            do{
                line = bufferedReader.readLine();
                Log.d("System out", "line "+line);
                if(line!=null){
                    buffer.append(line);
                }
            }while(line!=null);
            returnData = buffer.toString();
            bufferedReader.close();
            buffer = null;
        }catch (Exception e) {
            // TODO: handle exception
            returnData = null;
            Log.d("System out", "Error in ParsedData "+e.getMessage());
        }
        return returnData;
    }
}

**********************************************************************************


package com.rakesht.json;

import java.io.Serializable;

@SuppressWarnings("serial")
public class JSONParserDataActivity implements Serializable {

    private String Id, Name,Description, Image,
            Country, Latitude, Longitude, price;
    private String Includes, Excludes, Name, Id, Image;
     private String Id,Id,Id,Image,ImageCaption,hpCreatedDate;
    private String rms;
    private String facilityId,facName,facDescription,facImage,status,dateadded,datemodified;

    public String getFacilityId() {
        return facilityId;
    }

    public void setFacilityId(String facilityId) {
        this.facilityId = facilityId;
    }

    public String getFacName() {
        return facName;
    }

    public void setFacName(String facName) {
        this.facName = facName;
    }

    public String getFacDescription() {
        return facDescription;
    }

    public void setFacDescription(String facDescription) {
        this.facDescription = facDescription;
    }

    public String getFacImage() {
        return facImage;
    }

    public void setFacImage(String facImage) {
        this.facImage = facImage;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDateadded() {
        return dateadded;
    }

    public void setDateadded(String dateadded) {
        this.dateadded = dateadded;
    }

    public String getDatemodified() {
        return datemodified;
    }

    public void setDatemodified(String datemodified) {
        this.datemodified = datemodified;
    }

    public void setId(String Id) {
        this.Id = Id;
    }

    public String getId() {
        return Id;
    }

    public void setName(String Name) {
        this.Name = Name;
    }

    public String getName() {
        return Name;
    }

    public void setDescription(String Description) {
        this.Description = Description;
    }

    public String getDescription() {
        return Description;
    }

    public void setImage(StringImage) {
        this.Image = Image;
    }

    public String getImage() {
        return Image;
    }

    public void setCountry(String Country) {
        this.Country = Country;
    }

    public String getCountry() {
        return Country;
    }

    public void setLatitude(String Latitude) {
        this.Latitude = Latitude;
    }

    public String getLatitude() {
        return Latitude;
    }

    public void setLongitude(String Longitude) {
        this.Longitude = Longitude;
    }

    public String getLongitude() {
        return Longitude;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getPrice() {
        return price;
    }

    public void setIncludes(String Includes) {
        this.Includes = Includes;
    }

    public String getIncludes() {
        return Includes;
    }

    public void setExcludes(String Excludes) {
        this.Excludes = hrExcludes;
    }

    public String getExcludes() {
        return Excludes;
    }

    public void setName(String Name) {
        this.Name = Name;
    }

    public String getName() {
        return Name;
    }
   
}

**********************************************************************************
SigninActivity.java

package com.rakesht;

import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.rakesht.json.MyHttpConnection;

public class SigninActivity extends Activity implements OnClickListener{
    Intent i;
    Button Btn_signin,Btn_signup;
    TextView Txtv_forgot_password,Txtv_auto_login;
    EditText Edt_signin_email,Edt_signin_password;
    ImageView Imgv_canceltext_email,Imgv_canceltext_pass;
    CheckBox chkbx_autologin;
    LinearLayout lay_offer;
    private String username,password;
    String response = "";
    private ProgressDialog progressDialog;
    private boolean flag_response = false;
    ScrollView sign_in;
    private Boolean b1 = true, b2 = true, b3 = true, b4 = true, b5 = true;
    private NumberFormat nf;
   
    public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
              "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
              "\\@" +
              "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
              "(" +
              "\\." +
              "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
              ")+"
          );
    private Pattern pattern;
      private Matcher matcher;
    private SharedPreferences settings;
    private Editor editor;
      private static final String PASSWORD_PATTERN =
          "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
     
     
     
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sign_in);
        init();
        settings = getSharedPreferences("My_Pref", 0);
        editor=settings.edit();
        username=settings.getString("uname", "");
        password=settings.getString("pass", "");
        Log.i("System out","User name---2 : "+username);
        Log.i("System out","Password----2 : "+password);
       
//        if(((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).isActive())
//        {
//            lay_offer.setVisibility(View.INVISIBLE);
//        }
//        else
//        {
//            lay_offer.setVisibility(View.VISIBLE);
//        }
       
         if (username=="" || password=="")
            {
              
            }
            else
            {
                Log.i("System out","User name---3 : "+username);
                Log.i("System out","Password----3 : "+password);
               
                Edt_signin_email.setText(username);
                Edt_signin_password.setText(password);
                chkbx_autologin.setChecked(true);
                chkbx_autologin.setButtonDrawable(R.drawable.checkbox_selected_login);
               
            }

        //this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
       
       
        settings = getSharedPreferences("My_Pref", 0);
        editor=settings.edit();
      
       
        chkbx_autologin.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
           
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if(isChecked)
                {
//                    chkbx_autologin.setBackgroundResource(R.drawable.checkbox_selected_login);
                    chkbx_autologin.setButtonDrawable(R.drawable.checkbox_selected_login);
                }
                else
                {
                    chkbx_autologin.setButtonDrawable(R.drawable.checkbox_login);
                }
               
            }
        });
       
       
        final View activityRootView = findViewById(R.id.activityRoot);
       

       
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
                if (heightDiff > 100)
                {
                    lay_offer.setVisibility(View.INVISIBLE);
                }
                else
                {
                    lay_offer.setVisibility(View.VISIBLE);
                }
             }
        });
       
       
    }
   
   
   
   
   
//    public interface OnKeyboardVisibilityListener {
//
//        void onVisibilityChanged(boolean visible);
//    }
//
//    public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
//        final View activityRootView = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
//        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
//
//            private boolean wasOpened;
//
//        private final Rect r = new Rect();
//
//            @Override
//            public void onGlobalLayout() {
//                activityRootView.getWindowVisibleDisplayFrame(r);
//
//                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
//                boolean isOpen = heightDiff > 100;
//                if (isOpen == wasOpened) {
//                    lay_offer.setVisibility(View.VISIBLE);
//                    return;
//                }
//
//                else
//                {
//                    lay_offer.setVisibility(View.INVISIBLE);
//                }
//                wasOpened = isOpen;
//                listener.onVisibilityChanged(isOpen);
//            }
//        });
//    }
   
   
    public void init(){
       
       
        Btn_signin=(Button)findViewById(R.id.btn_signin);
        Btn_signup=(Button)findViewById(R.id.btn_signup);
        Txtv_forgot_password=(TextView)findViewById(R.id.tv_forgot_password);
        Edt_signin_email=(EditText)findViewById(R.id.edt_signin_email);
        Edt_signin_password=(EditText)findViewById(R.id.edt__signin_password);
        chkbx_autologin=(CheckBox)findViewById(R.id.imgv_auto_login);
        Imgv_canceltext_email=(ImageView)findViewById(R.id.imgv_cancel_email);
        Imgv_canceltext_pass=(ImageView)findViewById(R.id.imgv_cancel_pass);
        Btn_signin.setOnClickListener(this);
        Btn_signup.setOnClickListener(this);
        Txtv_forgot_password.setOnClickListener(this);
        chkbx_autologin.setOnClickListener(this);
        Imgv_canceltext_email.setOnClickListener(this);
         Imgv_canceltext_pass.setOnClickListener(this);
         Edt_signin_email.setOnClickListener(this);
         Edt_signin_password.setOnClickListener(this);
         sign_in=(ScrollView)findViewById(R.id.sign_in);
         lay_offer=(LinearLayout)findViewById(R.id.lay_offer);
         Edt_signin_email.addTextChangedListener(new TextWatcher()
         {
                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b1) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_canceltext_email.setVisibility(View.GONE);
                        } else {
                            Imgv_canceltext_email.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

         Edt_signin_email.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b1 = false;
                        Imgv_canceltext_email.setVisibility(View.GONE);
                        String st = Edt_signin_email.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Edt_signin_email.setText(st);
                        }
                    } else {
                        b1 = true;
                        String st = Edt_signin_email.getText().toString();
                        if (st.equals("")) {
                            Imgv_canceltext_email.setVisibility(View.GONE);
                        } else {
                            Imgv_canceltext_email.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
       
       
         Edt_signin_password.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b2) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_canceltext_pass.setVisibility(View.GONE);
                        } else {
                            Imgv_canceltext_pass.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

         Edt_signin_password.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b2 = false;
                        Imgv_canceltext_pass.setVisibility(View.GONE);
                        String st = Edt_signin_password.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Edt_signin_password.setText(st);
                        }
                    } else {
                        b2 = true;
                        String st = Edt_signin_password.getText().toString();
                        if (st.equals("")) {
                            Imgv_canceltext_pass.setVisibility(View.GONE);
                        } else {
                            Imgv_canceltext_pass.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
       
       
       
    }
   
    public void callDialog() {
        progressDialog = ProgressDialog.show(SigninActivity.this, null, "Loading...");
        progressDialog.setCancelable(true);
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                    getData();
            }
        }).start();
    }
   
    public void getData() {

        String signinemail = Edt_signin_email.getText().toString();
        String signinpassword = Edt_signin_password.getText().toString();
       
        String url="http://100.101.130.111/rakesh/json.php?action=login&userEmail="+signinemail+"&userPass="+signinpassword;

        Log.i("System out","url : "+url);
        response = MyHttpConnection.makeConnection(url);
        Log.i("System out","Response : "+response);
       
        if(response != null)
        {
           
            flag_response = true;
        }else {
            flag_response = false;
        }
        handler.sendEmptyMessage(0);
    }
   
    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if (progressDialog != null) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (flag_response) {
                   
                    RegisterNLJson();
                }else {
                    Toast.makeText(getApplicationContext(), "No data!", Toast.LENGTH_SHORT).show();
                }
            }
        };
    };
   
   
    public void RegisterNLJson() {
        JSONArray jsonArray;
        JSONObject jsonObject;
       
        try {
        jsonArray = new JSONArray(response);
       
        jsonObject = jsonArray.getJSONObject(0);
        if(jsonObject.has("status"))
        {
            String status=jsonObject.getString("status");
            Toast.makeText(getApplicationContext(), status, Toast.LENGTH_SHORT).show();
        }   
        else
        {
            Toast.makeText(getApplicationContext(), " Successfully Login", Toast.LENGTH_SHORT).show();
            editor.putString("userid", jsonObject.getString("userId"));
            editor.putString("userFirstName", jsonObject.getString("userFirstName"));
            editor.putString("userLastName", jsonObject.getString("userLastName"));
            editor.putString("userPhone", jsonObject.getString("userPhone"));
            editor.putString("userEmail", jsonObject.getString("userEmail"));
            editor.putString("userPass", jsonObject.getString("userPass"));
            editor.putString("userAddress", jsonObject.getString("userAddress"));
            editor.putString("userCity", jsonObject.getString("userCity"));
            editor.putString("userState", jsonObject.getString("userState"));
            editor.putString("userZip", jsonObject.getString("userZip"));
            editor.putString("userCountry", jsonObject.getString("userCountry"));
            editor.commit();

            i=new Intent(this,itemActivity.class);
            startActivity(i);
            //SigninActivity.this.finish();
        }   
           
//        SigninActivity.this.finish();
       
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
       
    }
   
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
       
        String signinemail = Edt_signin_email.getText().toString();
        String signinpassword = Edt_signin_password.getText().toString();
       
        if(v==Btn_signin)
        {
            if(signinemail.equals("") || signinpassword.equals(""))
            {
                if (signinemail.equals(""))
                {
                    Toast.makeText(SigninActivity.this, "Please enter email id",    Toast.LENGTH_LONG).show();

                }
               
                /*else if (signinemail.length()>0)
                {
                    Imgv_canceltext_email.setVisibility(View.VISIBLE);

                }*/
                else if (signinpassword.equals("")||signinpassword.length()<6)
                {
                    Toast.makeText(SigninActivity.this, "Please enter password",Toast.LENGTH_LONG).show();

                }
               
                else if (signinpassword.length()<6)
                {
                    Toast.makeText(SigninActivity.this, "Please enter password with minimum 6 character",Toast.LENGTH_LONG).show();

                }
               
               
            }
            else if (!checkEmail(signinemail))
            {
                Toast.makeText(SigninActivity.this, "Please enter valid email id",Toast.LENGTH_LONG).show();
            }
           
            /*else if(v==Edt_signin_email)
            {
                Imgv_canceltext_email.setVisibility(View.VISIBLE);
            }
            else if(v==Edt_signin_password)
            {
                Imgv_canceltext_pass.setVisibility(View.VISIBLE);
            }*/
           
            else
            {
                if(chkbx_autologin.isChecked())
                {
                    editor.putBoolean("remember", true);
                    editor.putString("username", signinemail);
                    editor.putString("password", signinpassword);
                    editor.putString("uname", signinemail);
                    editor.putString("pass", signinpassword);
                    editor.commit();
                }
               
                if(chkbx_autologin.isChecked()==false)
                {
                    editor.remove("remember");
                    editor.remove("username");
                    editor.remove("password");
                    editor.remove("uname");
                    editor.remove("pass");
                    editor.commit();
                }
                callDialog();
            }
           
           
        }
       
       
        else if(v==Imgv_canceltext_email)
        {
            Edt_signin_email.setText("");
        }
       
        else if(v==Imgv_canceltext_pass)
        {
            Edt_signin_password.setText("");
        }
       
        /*else if(v==chkbx_autologin)
        {
            if(chkbx_autologin.isChecked())
            {
                    chkbx_autologin.setButtonDrawable(R.drawable.checkbox_selected_login);
            }
            else
            {
                chkbx_autologin.setButtonDrawable(R.drawable.checkbox_login);
            }
        }*/
        else if(v==Btn_signup)
        {
            i=new Intent(this,SignupActivity.class);
            startActivity(i);
            //SigninActivity.this.finish();
        }
        else if(v==Txtv_forgot_password)
        {
            i=new Intent(this,ForgotPasswordActivity.class);
            startActivity(i);
            //SigninActivity.this.finish();
        }
       
       
       
    }

   
   
   
   
   
   
    private boolean checkEmail(String email) {
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }
   
     public SigninActivity()
     {
          pattern = Pattern.compile(PASSWORD_PATTERN);
      }
      public boolean validate(String signinpassword)
      {
          matcher = pattern.matcher(signinpassword);
          return matcher.matches();
      }

   
     /*@Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                // Finish activity on back button
//                this.finish();
                overridePendingTransition(R.anim.slide_in_left,
                        R.anim.slide_out_right);
            }
            return super.onKeyDown(keyCode, event);
        }
    */     
     
}

**********************************************************************************







SignupActivity.java



package com.r;akesht

import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.rakesht.json.MyHttpConnection;

public class SignupActivity extends Activity implements OnClickListener{
    Intent i;
    Button btn_signup_submit,btn_signup_cancel;
    ImageView Imgv_txtclear_fname,Imgv_txtclear_lname,Imgv_txtclear_email,Imgv_txtclear_phone,
    Imgv_txtclear_pass,Imgv_txtclear_confpass;
    TextView Tv_signup_back, Tv_signup_header;
    EditText Tv_first_name,Tv_last_name,Tv_phone,Tv_email,Tv_password,Tv_confirm_password;
    String response = "",firstname,lastname,email,phone,password,confirmpassword,mid;
    private ProgressDialog progressDialog;
    private boolean flag_response = false, b1 = true, b2 = true, b3 = true, b4 = true, b5 = true,b6=true;
   
//    Boolean update = false;
//    DBAdapter db;
    ArrayList<HashMap<String, String>> userdetail;
    ArrayAdapter ayArrayAdapter;
    String phonenoStr = "^[+][0-9]{10,13}$";
//     AlertDialog.Builder builder = new AlertDialog.Builder(this);
     public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
              "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
              "\\@" +
              "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
              "(" +
              "\\." +
              "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
              ")+"
          );
   
     private Pattern pattern;
      private Matcher matcher;
    private SharedPreferences settings;
    private Editor editor;
      private static final String PASSWORD_PATTERN =
//         "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
      "((?=.*[@#$%]).{6,20})";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
       setContentView(R.layout.sign_up);
      
       //this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
       init();
      
       settings = getSharedPreferences("My_Pref", 0);
        editor=settings.edit();
      
      
    }

    public void  init(){
       
        btn_signup_submit=(Button)findViewById(R.id.btn_submit);
           btn_signup_cancel=(Button)findViewById(R.id.btn_cancel);
//           Tv_signup_header=(TextView)findViewById(R.id.txtheaderResTitle);
          
           Tv_first_name=(EditText)findViewById(R.id.edt_signup_firstname);
           Tv_last_name=(EditText)findViewById(R.id.edt_signup_lastname);
           Tv_phone=(EditText)findViewById(R.id.edt_signup_phone);
           Tv_email=(EditText)findViewById(R.id.edt_signup_email);
           Tv_password=(EditText)findViewById(R.id.edt_signup_password);
           Tv_confirm_password=(EditText)findViewById(R.id.edt_signup_confirm_pass);
           Imgv_txtclear_fname=(ImageView)findViewById(R.id.imgv_cancel_fname);
           Imgv_txtclear_lname=(ImageView)findViewById(R.id.imgv_cancel_lname);
           Imgv_txtclear_email=(ImageView)findViewById(R.id.imgv_cancel_email);
           Imgv_txtclear_phone=(ImageView)findViewById(R.id.imgv_cancel_phone);
           Imgv_txtclear_pass=(ImageView)findViewById(R.id.imgv_cancel_pass);
           Imgv_txtclear_confpass=(ImageView)findViewById(R.id.imgv_cancel_confpass);
          
//           Tv_signup_header.setText("Sign Up");
//           Tv_signup_back=(TextView)findViewById(R.id.back);
//           Tv_signup_back.setVisibility(View.GONE);
           btn_signup_submit.setOnClickListener(this);
           btn_signup_cancel.setOnClickListener(this);
           Imgv_txtclear_fname.setOnClickListener(this);
           Imgv_txtclear_lname.setOnClickListener(this);
           Imgv_txtclear_email.setOnClickListener(this);
           Imgv_txtclear_phone.setOnClickListener(this);
           Imgv_txtclear_pass.setOnClickListener(this);
           Imgv_txtclear_confpass.setOnClickListener(this);
         
          
           Tv_first_name.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b1) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_txtclear_fname.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_fname.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

           Tv_first_name.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b1 = false;
                        Imgv_txtclear_fname.setVisibility(View.GONE);
                        String st = Tv_first_name.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Tv_first_name.setText(st);
                        }
                    } else {
                        b1 = true;
                        String st = Tv_first_name.getText().toString();
                        if (st.equals("")) {
                            Imgv_txtclear_fname.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_fname.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
           
           Tv_last_name.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b2) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_txtclear_lname.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_lname.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

           Tv_last_name.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b2 = false;
                        Imgv_txtclear_lname.setVisibility(View.GONE);
                        String st = Tv_last_name.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Tv_last_name.setText(st);
                        }
                    } else {
                        b2 = true;
                        String st = Tv_last_name.getText().toString();
                        if (st.equals("")) {
                            Imgv_txtclear_lname.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_lname.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
           Tv_phone.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b3) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_txtclear_phone.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_phone.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

           Tv_phone.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b3 = false;
                        Imgv_txtclear_phone.setVisibility(View.GONE);
                        String st = Tv_phone.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Tv_phone.setText(st);
                        }
                    } else {
                        b3 = true;
                        String st = Tv_phone.getText().toString();
                        if (st.equals("")) {
                            Imgv_txtclear_phone.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_phone.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
           Tv_email.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b4) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_txtclear_email.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_email.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

           Tv_email.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b4 = false;
                        Imgv_txtclear_email.setVisibility(View.GONE);
                        String st = Tv_email.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Tv_email.setText(st);
                        }
                    } else {
                        b4 = true;
                        String st = Tv_email.getText().toString();
                        if (st.equals("")) {
                            Imgv_txtclear_email.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_email.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
           Tv_password.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b5) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_txtclear_pass.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_pass.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

           Tv_password.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b5 = false;
                        Imgv_txtclear_pass.setVisibility(View.GONE);
                        String st = Tv_password.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Tv_password.setText(st);
                        }
                    } else {
                        b5 = true;
                        String st = Tv_password.getText().toString();
                        if (st.equals("")) {
                            Imgv_txtclear_pass.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_pass.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
           Tv_confirm_password.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before,
                        int count) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (b6) {
                        String st = s.toString();
                        if (st.equals("")) {
                            Imgv_txtclear_confpass.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_confpass.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

           Tv_confirm_password.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // TODO Auto-generated method stub
                    // show/hide image button for end of the text box
                    if (!hasFocus) {
                        b6 = false;
                        Imgv_txtclear_confpass.setVisibility(View.GONE);
                        String st = Tv_confirm_password.getText().toString();
                        if (st.equals("")) {
                        } else {
                            st = st.replace(",", "");
                            /*Double d = Double.parseDouble(st);
                            String s1 = nf.format(d);*/
                            Tv_confirm_password.setText(st);
                        }
                    } else {
                        b6 = true;
                        String st = Tv_confirm_password.getText().toString();
                        if (st.equals("")) {
                            Imgv_txtclear_confpass.setVisibility(View.GONE);
                        } else {
                            Imgv_txtclear_confpass.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
       
          
          
    }
   
   
    public void callDialog() {
        progressDialog = ProgressDialog.show(SignupActivity.this, null, "Loading...");
        progressDialog.setCancelable(true);
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                    getData();
            }
        }).start();
    }
   
    public void getData() {

        firstname=Tv_first_name.getText().toString();
        lastname=Tv_last_name.getText().toString();
        email=Tv_email.getText().toString();
        phone=Tv_phone.getText().toString();
        password=Tv_password.getText().toString();
       
//        String url="http://100.101.130.200/rakesht/json.php?action=Registernewsletter&json=[{\"nlSubscriberFN\":\""+firstname+"\",\"nlSubscriberLN\":\""+lastname+"\",\"nlSubscriberEmail\":\""+email+"\",\"age\":\""+age+"\",\"country\":\""+country+"\",\"sex\":\""+gender+"\"}]";
        String url="http://100.101.130.200/rakesht/json.php?action=insertusers&json=[{\"userFirstName\":\""+firstname+"\",\"userLastName\":\""+lastname+"\",\"userPhone\":\""+phone+"\",\"userEmail\":\""+email+"\",\"userPass\":\""+password+"\"}]";
//        String url="http://100.101.130.200/rakesht/json.php?action=insertusers&json=[{%22userFirstName%22:%22a%22,%22userLastName%22:%22b%22,%22userPhone%22:%229876543214%22,%22userEmail%22:%22abc@gmail.com%22,%22userPass%22:%22abc%22}]";
       

        response =MyHttpConnection.makeConnection(url);
        Log.i("System out","Response : "+response);

        if(response != null){
            flag_response = true;
        }else {
            flag_response = false;
        }
        handler.sendEmptyMessage(0);
    }
   
    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if (progressDialog != null) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (flag_response) {
                   
                    RegisterNLJson();
                }else {
                    Toast.makeText(getApplicationContext(), "No data!", Toast.LENGTH_SHORT).show();
                }
            }
        };
    };
   
   
    public void RegisterNLJson() {
        JSONArray jsonArray;
        JSONObject jsonObject;
       
        try {
        jsonArray = new JSONArray(response);
       
        jsonObject = jsonArray.getJSONObject(0);
        Log.v("System out","Response : in fun"+jsonObject);
        String status=jsonObject.getString("userId");
       
        if(status!=null)
        {
        Log.v("System out","Response : in status"+status);
        Toast.makeText(getApplicationContext(), "Signup successfully.", Toast.LENGTH_SHORT).show();
       
        editor.putString("uname", Tv_email.getText().toString());
        editor.putString("pass", Tv_password.getText().toString());
        editor.commit();
       
        i=new Intent(this,SigninActivity.class);
        startActivity(i);
//        SignupActivity.this.finish();
        }else{
            Toast.makeText(getApplicationContext(), status, Toast.LENGTH_SHORT).show();
        }
           
       
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }
   
   
   
   
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
       
         String firstname=Tv_first_name.getText().toString();
            String lastname=Tv_last_name.getText().toString();
            String phone=Tv_phone.getText().toString();
            String email=Tv_email.getText().toString();
            String password=Tv_password.getText().toString();
            String confirmpassword=Tv_confirm_password.getText().toString();
           
           
             if(v==btn_signup_cancel){
//                SignupActivity.this.finish();
                i=new Intent(this,SigninActivity.class);
                startActivity(i);
            }
           
             else if(v==Imgv_txtclear_fname){
                 Tv_first_name.setText("");
               
             }
             else if(v==Imgv_txtclear_lname){
                 Tv_last_name.setText("");
             }
             else if(v==Imgv_txtclear_email){
               
                 Tv_email.setText("");
               
             }
             else if(v==Imgv_txtclear_phone){
                 Tv_phone.setText("");
             }
             else if(v==Imgv_txtclear_pass){
                 Tv_password.setText("");
             }
             else if(v==Imgv_txtclear_confpass){
                 Tv_confirm_password.setText("");
             }
       
             else    if(v==btn_signup_submit){
           
           
            if (firstname.equals("") || lastname.equals("")
                    || phone.equals("")||email.equals("")|| password.equals("")|| confirmpassword.equals("")) {
                if (firstname.equals("")) {
                    Toast.makeText(SignupActivity.this, "Please provide first name",
                            Toast.LENGTH_LONG).show();

                }
                else if (lastname.equals("")) {
                    Toast.makeText(SignupActivity.this, "Please provide last name",
                            Toast.LENGTH_LONG).show();

                }
               
               
                else if (email.equals("")) {
                    Toast.makeText(SignupActivity.this, "Please provide email id",
                            Toast.LENGTH_LONG).show();

                }
                /*else if (!checkEmail(email)) {
                    Toast.makeText(SignupActivity.this, "Please provide valid email id",
                            Toast.LENGTH_LONG).show();
                }*/
               
               
               
                else if (phone.equals("")) {
                    Toast.makeText(SignupActivity.this, "Please provide phone no",
                            Toast.LENGTH_LONG).show();

                }
               
                /*else if(phone.matches(phonenoStr)==false  ) {
                            Toast.makeText(SignupActivity.this," Please provide phone no",Toast.LENGTH_SHORT).show();
                           // am_checked=0;
                        }*/
               
                /*else if(phone.length()<10||phone.length()>15) {
                    Toast.makeText(SignupActivity.this," Please provide valid phone no",Toast.LENGTH_SHORT).show();
                   // am_checked=0;
                }*/
               
                else if (password.equals("")) {
                    Toast.makeText(SignupActivity.this, "Please provide password",
                            Toast.LENGTH_LONG).show();

                }
                else if (password.length()<6) {
                    Toast.makeText(SignupActivity.this, "Please provide password with minimum 6 character",
                            Toast.LENGTH_LONG).show();

                }
               
                else if (confirmpassword.equals("")) {
                    Toast.makeText(SignupActivity.this, "Please provide confirm password",
                            Toast.LENGTH_LONG).show();

                }
               
               
               
            }   
               
           
             else if (!checkEmail(email)) {
                    Toast.makeText(SignupActivity.this, "Please provide valid email id",
                            Toast.LENGTH_LONG).show();
                }
           
           
            else if(phone.length()<12||phone.length()>15) {
                Toast.makeText(SignupActivity.this," Please provide valid phone no",Toast.LENGTH_SHORT).show();
               // am_checked=0;
            }
                   
           
             else if (password.length()<6) {
                    Toast.makeText(SignupActivity.this, "Please provide password with minimum 6 character",
                            Toast.LENGTH_LONG).show();

                }
           
             else if (!confirmpassword .equals(password)) {
               
                 Toast.makeText(SignupActivity.this, "Password and Confirm password should be match",
                            Toast.LENGTH_LONG).show();
               
                /* AlertDialog alertDialog = new AlertDialog.Builder(SignupActivity.this).create();
                    alertDialog.setTitle("oops!");
                    alertDialog.setMessage("Passwords do not match");
                    alertDialog.setButton("Ok",
                    new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                              //dismiss the dialog 
                            }
                        });
                    alertDialog.show();*/

                }
           
           
           
           
             else{
               
                 callDialog();   
   
               
             }
                       
                   
        }
           
       
    }
   
    private boolean checkEmail(String email) {
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }

    public SignupActivity(){
          pattern = Pattern.compile(PASSWORD_PATTERN);
      }
      public boolean validate(String password){
           
          matcher = pattern.matcher(password);
          return matcher.matches();

      }

}

*********************************************************************************
UpdateProfile

import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class UpdateProfileActivity  extends Activity implements OnClickListener{

TextView Tv_updateprofile_back,Tv_updateprofile_header;
Intent i;
LinearLayout Lay_menufooter;
Button Btn_submit,Btn_cancel;
ImageView Imgv_contctdetails_bookingdetails,
Imgv_txtclear_fname,Imgv_txtclear_lname,Imgv_txtclear_email,Imgv_txtclear_address,
Imgv_txtclear_zipcode,Imgv_txtclear_city,Imgv_txtclear_country,Imgv_txtclear_phone,Imgv_dropdown;
TextView Tv_cntctdetail_back,Tv_cntctdetail_header,Tv_contctdetails_bookingdetails,
Tv_first_name,Tv_last_name,Tv_phone,Tv_email,Tv_address,Tv_zip,Tv_city,Tv_country;
private SharedPreferences preferences;
String response = "",firstname,lastname,email,emailaddress,address,zipcode,city,country,phone,userid;
private Editor editor;
    Footer footer;
private ProgressDialog progressDialog;
private boolean flag_response = false, b1 = true, b2 = true, b3 = true, b4 = true, b5 = true,b6=true
,b7=true,b8=true;
String phonenoStr = "^[+][0-9]{10,13}$";
Pattern pattern = Pattern.compile("^[+][0-9]{10,13}$");
String[] countryname = new String[] {
"Afghanistan", "Albania","Algeria", "Angola","Anguilla","Antarctica","Argentina","Aruba","Australia","Austria",
"Azerbaijan","Bahamas", "Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bhutan","Bolivia",
"Bosnia and Herzegovina","Botswana","Brazil","Brunei","Bulgaria","Burkina Faso","Burma","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Central African Republic","Chad","Chile",
"China","Colombia","Comoros","Congo","Costa Rica","Cote d'Ivoire","Croatia","Cuba","Curacao","Cyprus","Czech Rpublic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea",
"Eritrea","Estonia","Ethiopia","Fiji","Finland","France","Gabon","Gambia","Georgia","Germany","Ghana","Greece",
"Grenada","Guatemala","Guinea","Guinea-Bissau","Guyana", "Haiti","Holy See","Honduras","Hong Kong","Hungary","Iceland",
"India","Indonesia","Iran","Iraq","Ireland","Israel","Italy","Jamaica","Japan","Jordan","Kazakhstan","Kenya","Kiribati",
"Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya",
"Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta",
"Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro",
"Morocco","Mozambique","Namibia","Nauru","Nepal","Netherlands","Netherlands Antilles","New Zealand","Nicaragua",
"Niger","Nigeria","North Korea","Norway","Oman","Pakistan","Palau","Palestinian Territories","Panama","Papua New Guinea",
"Paraguay","Peru","Philippines","Poland","Portugal","Qatar","Romania","Russia","Rwanda","Saint Kitts and Nevis",
"Saint Lucia","Saint Vincent and the Grenadines","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal",
"Serbia","Seychelles","Sierra Leone","Singapore","Sint Maarten","Slovakia","Slovenia","Solomon Islands","Somalia",
"South Africa","South Korea","South Sudan","Spain","Sri Lanka","Sudan"," Suriname","Swaziland","Sweden","Switzerland",
"Syria","Taiwan","Tajikistan","Tanzania","Thailand",
"Timor-Leste","Togo","Tonga","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States","Uruguay", "Uzbekistan","Vanuatu", "Venezuela",
"Vietnam","Yemen","Zambia","Zimbabwe"};
 String pos;

public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
         "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
         "\\@" +
         "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
         "(" +
         "\\." +
         "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
         ")+"
     );
private ImageView Imgv_selected;

@Override
public void onStart()
{

       super.onStart();
       Logout.activity21 = UpdateProfileActivity.this;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.update_profile);
preferences = getSharedPreferences("My_Pref", 0);
editor=preferences.edit();

userid=preferences.getString("userid","");
firstname=preferences.getString("userFirstName","");
lastname=preferences.getString("userLastName","");
emailaddress=preferences.getString("userEmail","");
address=preferences.getString("userAddress","");
zipcode=preferences.getString("userZip","");
city=preferences.getString("userCity","");
country=preferences.getString("userCountry","");
phone=preferences.getString("userPhone","");
// this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
init();
Imgv_selected=(ImageView)findViewById(Footer.SETTING_ID);
Imgv_selected.setImageResource(R.drawable.icon_setting_selected);

}

public void init(){
Tv_updateprofile_back=(TextView)findViewById(R.id.back);
Tv_updateprofile_header=(TextView)findViewById(R.id.txtheaderResTitle);

Tv_first_name=(EditText)findViewById(R.id.edt_updprfl_firstname);
      Tv_last_name=(EditText)findViewById(R.id.edt_updprfl_lastname);
      Tv_phone=(EditText)findViewById(R.id.edt_updprfl_phoneno);
      Tv_email=(EditText)findViewById(R.id.edt_updprfl_email);
      Tv_address=(EditText)findViewById(R.id.edt_updprfl_address);
      Tv_zip=(EditText)findViewById(R.id.edt_updprfl_zipcode);
      Tv_city=(EditText)findViewById(R.id.edt_updprfl_city);
      Tv_country=(TextView)findViewById(R.id.edt_updprfl_country);
      Btn_submit=(Button)findViewById(R.id.btn_submit);
      Btn_cancel=(Button)findViewById(R.id.btn_cancel);
      Lay_menufooter=(LinearLayout)findViewById(R.id.menufooter);
     
      Tv_first_name.setText(firstname);
      Tv_last_name.setText(lastname);
      Tv_email.setText(emailaddress);
      Tv_address.setText(address);
      Tv_zip.setText(zipcode);
      Tv_city.setText(city);
      Tv_country.setText(country);
      Tv_phone.setText(phone);
     
     
      Imgv_txtclear_fname=(ImageView)findViewById(R.id.imgv_cancel_fname);
      Imgv_txtclear_lname=(ImageView)findViewById(R.id.imgv_cancel_lname);
      Imgv_txtclear_email=(ImageView)findViewById(R.id.imgv_cancel_email);
      Imgv_txtclear_phone=(ImageView)findViewById(R.id.imgv_cancel_phone);
      Imgv_txtclear_address=(ImageView)findViewById(R.id.imgv_cancel_address);
      Imgv_txtclear_zipcode=(ImageView)findViewById(R.id.imgv_cancel_zipcode);
      Imgv_txtclear_city=(ImageView)findViewById(R.id.imgv_cancel_city);
      Imgv_txtclear_country=(ImageView)findViewById(R.id.imgv_cancel_country);
      Imgv_dropdown=(ImageView)findViewById(R.id.imgv_dropdown);
     
Tv_updateprofile_header.setText("Update Profile");

Tv_updateprofile_back.setOnClickListener(this);
Btn_submit.setOnClickListener(this);
Btn_cancel.setOnClickListener(this);
Tv_country.setOnClickListener(this);
  Imgv_txtclear_fname.setOnClickListener(this);
      Imgv_txtclear_lname.setOnClickListener(this);
//       Imgv_txtclear_email.setOnClickListener(this);
      Imgv_txtclear_phone.setOnClickListener(this);
      Imgv_txtclear_address.setOnClickListener(this);
      Imgv_txtclear_zipcode.setOnClickListener(this);
      Imgv_txtclear_city.setOnClickListener(this);
      Imgv_txtclear_country.setOnClickListener(this);
      Imgv_dropdown.setOnClickListener(this);
     
 Tv_first_name.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
// Lay_menufooter.setVisibility(View.GONE);
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (b1) {
String st = s.toString();
if (st.equals("")) {
Imgv_txtclear_fname.setVisibility(View.GONE);
} else {
Imgv_txtclear_fname.setVisibility(View.VISIBLE);
}
}
}
});

      Tv_first_name.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
// Lay_menufooter.setVisibility(View.GONE);
if (!hasFocus) {
b1 = false;
Imgv_txtclear_fname.setVisibility(View.GONE);
String st = Tv_first_name.getText().toString();
if (st.equals("")) {
} else {
st = st.replace(",", "");
/*Double d = Double.parseDouble(st);
String s1 = nf.format(d);*/
Tv_first_name.setText(st);
}
} else {
b1 = true;
String st = Tv_first_name.getText().toString();
if (st.equals("")) {
Imgv_txtclear_fname.setVisibility(View.GONE);
} else {
Imgv_txtclear_fname.setVisibility(View.VISIBLE);
}
}
}
});

     
      Tv_last_name.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (b2) {
String st = s.toString();
if (st.equals("")) {
Imgv_txtclear_lname.setVisibility(View.GONE);
} else {
Imgv_txtclear_lname.setVisibility(View.VISIBLE);
}
}
}
});

      Tv_last_name.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (!hasFocus) {
b2 = false;
Imgv_txtclear_lname.setVisibility(View.GONE);
String st = Tv_last_name.getText().toString();
if (st.equals("")) {
} else {
st = st.replace(",", "");
/*Double d = Double.parseDouble(st);
String s1 = nf.format(d);*/
Tv_last_name.setText(st);
}
} else {
b2 = true;
String st = Tv_last_name.getText().toString();
if (st.equals("")) {
Imgv_txtclear_lname.setVisibility(View.GONE);
} else {
Imgv_txtclear_lname.setVisibility(View.VISIBLE);
}
}
}
});

      Tv_phone.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (b3) {
String st = s.toString();
if (st.equals("")) {
Imgv_txtclear_phone.setVisibility(View.GONE);
} else {
Imgv_txtclear_phone.setVisibility(View.VISIBLE);
}
}
}
});

      Tv_phone.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (!hasFocus) {
b3 = false;
Imgv_txtclear_phone.setVisibility(View.GONE);
String st = Tv_phone.getText().toString();
if (st.equals("")) {
} else {
st = st.replace(",", "");
/*Double d = Double.parseDouble(st);
String s1 = nf.format(d);*/
Tv_phone.setText(st);
}
} else {
b3 = true;
String st = Tv_phone.getText().toString();
if (st.equals("")) {
Imgv_txtclear_phone.setVisibility(View.GONE);
} else {
Imgv_txtclear_phone.setVisibility(View.VISIBLE);
}
}
}
});

     Tv_email.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (b4) {
String st = s.toString();
if (st.equals("")) {
Imgv_txtclear_email.setVisibility(View.GONE);
} else {
Imgv_txtclear_email.setVisibility(View.GONE);
}
}
}
});

      Tv_email.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (!hasFocus) {
b4 = false;
Imgv_txtclear_email.setVisibility(View.GONE);
String st = Tv_email.getText().toString();
if (st.equals("")) {
} else {
st = st.replace(",", "");
/*Double d = Double.parseDouble(st);
String s1 = nf.format(d);*/
Tv_email.setText(st);
}
} else {
b4 = true;
String st = Tv_email.getText().toString();
if (st.equals("")) {
Imgv_txtclear_email.setVisibility(View.GONE);
} else {
Imgv_txtclear_email.setVisibility(View.GONE);
}
}
}
});

      Tv_address.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (b5) {
String st = s.toString();
if (st.equals("")) {
Imgv_txtclear_address.setVisibility(View.GONE);
} else {
Imgv_txtclear_address.setVisibility(View.VISIBLE);
}
}
}
});

      Tv_address.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (!hasFocus) {
b5 = false;
Imgv_txtclear_address.setVisibility(View.GONE);
String st = Tv_address.getText().toString();
if (st.equals("")) {
} else {
st = st.replace(",", "");
/*Double d = Double.parseDouble(st);
String s1 = nf.format(d);*/
Tv_address.setText(st);
}
} else {
b5 = true;
String st = Tv_address.getText().toString();
if (st.equals("")) {
Imgv_txtclear_address.setVisibility(View.GONE);
} else {
Imgv_txtclear_address.setVisibility(View.VISIBLE);
}
}
}
});

      Tv_zip.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (b6) {
String st = s.toString();
if (st.equals("")) {
Imgv_txtclear_zipcode.setVisibility(View.GONE);
} else {
Imgv_txtclear_zipcode.setVisibility(View.VISIBLE);
}
}
}
});

      Tv_zip.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (!hasFocus) {
b6 = false;
Imgv_txtclear_zipcode.setVisibility(View.GONE);
String st = Tv_zip.getText().toString();
if (st.equals("")) {
} else {
st = st.replace(",", "");
/*Double d = Double.parseDouble(st);
String s1 = nf.format(d);*/
Tv_zip.setText(st);
}
} else {
b6 = true;
String st = Tv_zip.getText().toString();
if (st.equals("")) {
Imgv_txtclear_zipcode.setVisibility(View.GONE);
} else {
Imgv_txtclear_zipcode.setVisibility(View.VISIBLE);
}
}
}
});

      Tv_city.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (b7) {
String st = s.toString();
if (st.equals("")) {
Imgv_txtclear_city.setVisibility(View.GONE);
} else {
Imgv_txtclear_city.setVisibility(View.VISIBLE);
}
}
}
});

     Tv_city.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (!hasFocus) {
b7 = false;
Imgv_txtclear_city.setVisibility(View.GONE);
String st = Tv_city.getText().toString();
if (st.equals("")) {
} else {
st = st.replace(",", "");
/*Double d = Double.parseDouble(st);
String s1 = nf.format(d);*/
Tv_city.setText(st);
}
} else {
b7 = true;
String st = Tv_city.getText().toString();
if (st.equals("")) {
Imgv_txtclear_city.setVisibility(View.GONE);
} else {
Imgv_txtclear_city.setVisibility(View.VISIBLE);
}
}
}
});

     Tv_country.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (b8) {
String st = s.toString();
if (st.equals("")) {
Imgv_txtclear_country.setVisibility(View.GONE);
} else {
Imgv_txtclear_country.setVisibility(View.VISIBLE);
}
}
}
});

     Tv_country.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
// show/hide image button for end of the text box
if (!hasFocus) {
b8 = false;
Imgv_txtclear_country.setVisibility(View.GONE);
String st = Tv_country.getText().toString();
if (st.equals("")) {
} else {
st = st.replace(",", "");
/*Double d = Double.parseDouble(st);
String s1 = nf.format(d);*/
Tv_country.setText(st);
}
} else {
b8 = true;
String st = Tv_country.getText().toString();
if (st.equals("")) {
Imgv_txtclear_country.setVisibility(View.GONE);
} else {
Imgv_txtclear_country.setVisibility(View.VISIBLE);
}
}
}
});

     
     



}


public void callDialog() {
progressDialog = ProgressDialog.show(UpdateProfileActivity.this, null, "Loading...");
progressDialog.setCancelable(true);
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
getData();
}
}).start();
}

public void getData() {

   String firstname=Tv_first_name.getText().toString();
String lastname=Tv_last_name.getText().toString();
   String email=Tv_email.getText().toString();
String phone=Tv_phone.getText().toString();
String address=Tv_address.getText().toString();
String zip=Tv_zip.getText().toString();
String city=Tv_city.getText().toString();
String country=Tv_country.getText().toString();

String url="http://100.101.145.211/testapp/json.php?action=editusers&userId="+userid+"&json=[{\"userFirstName\":\""+firstname+"\",\"userLastName\":\""+lastname+"\",\"userPhone\":\""+phone+"\",\"userAddress\":\""+address+"\",\"userCity\":\""+city+"\",\"userState\":\"\",\"userZip\":\""+zip+"\",\"userCountry\":\""+country+"\"}]";
response =MyHttpConnection.makeConnection(url);
Log.i("System out","Response : "+response);

if(response != null){
flag_response = true;
}else {
flag_response = false;
}
handler.sendEmptyMessage(0);
}

Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (flag_response) {

RegisterNLJson();
}else {
Toast.makeText(getApplicationContext(), "No data!", Toast.LENGTH_SHORT).show();
}
}
};
};


public void RegisterNLJson() {
JSONArray jsonArray;
JSONObject jsonObject;

try {
jsonArray = new JSONArray(response);

jsonObject = jsonArray.getJSONObject(0);
Log.v("System out","Response : in fun"+jsonObject);
String status=jsonObject.getString("userId");

if(status!=null)
{
editor.putString("userid", jsonObject.getString("userId"));
editor.putString("userFirstName", jsonObject.getString("userFirstName"));
editor.putString("userLastName", jsonObject.getString("userLastName"));
editor.putString("userPhone", jsonObject.getString("userPhone"));
editor.putString("userEmail", jsonObject.getString("userEmail"));
editor.putString("userPass", jsonObject.getString("userPass"));
editor.putString("userAddress", jsonObject.getString("userAddress"));
editor.putString("userCity", jsonObject.getString("userCity"));
editor.putString("userState", jsonObject.getString("userState"));
editor.putString("userZip", jsonObject.getString("userZip"));
editor.putString("userCountry", jsonObject.getString("userCountry"));
editor.commit();


/*editor.putString("userid", userid);
editor.putString("userFirstName",firstname );
editor.putString("userLastName",lastname );
editor.putString("userPhone", phone);
editor.putString("userAddress", address);
editor.putString("userCity", city);
editor.putString("userZip", zipcode);
editor.putString("userCountry",country );
editor.commit(); */

Log.v("System out","Response : in status"+status);
            Toast.makeText(getApplicationContext(), "Update successfully", Toast.LENGTH_SHORT).show();
           
            Intent i=new Intent(this,SettingsActivity.class);
startActivity(i);
//            UpdateProfileActivity.this.finish();
// SignupActivity.this.finish();
}else{
Toast.makeText(getApplicationContext(), status, Toast.LENGTH_SHORT).show();
}


} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}





@Override
public void onClick(View v) {
// TODO Auto-generated method stub

String firstname=Tv_first_name.getText().toString();
String lastname=Tv_last_name.getText().toString();
   String email=Tv_email.getText().toString();
String phone=Tv_phone.getText().toString();
String address=Tv_address.getText().toString();
String zip=Tv_zip.getText().toString();
String city=Tv_city.getText().toString();
String country=Tv_country.getText().toString();


if(v==Tv_updateprofile_back){
UpdateProfileActivity.this.finish();
}

else if(v==Btn_cancel){
UpdateProfileActivity.this.finish();
}
else if(v==Tv_country||v==Imgv_dropdown)
{
// AlertDialog.Builder builder = new AlertDialog.Builder(UpdateProfileActivity.this);
// builder.setTitle("Country");
// builder.setItems(countryname, new DialogInterface.OnClickListener()
// {
// public void onClick(DialogInterface dialog, int item)
// {
// if(Tv_country.getText().toString().equalsIgnoreCase(""))
// {}
// else
// {
// }
// Tv_country.setText(countryname[item]);
// }
// });
//
// AlertDialog alert = builder.create();
// alert.show();


final ArrayList<String> stringList = new ArrayList<String>(Arrays.asList(countryname));

AlertDialog.Builder dialog1 = new AlertDialog.Builder(UpdateProfileActivity.this);
dialog1.setTitle("Select Country");
   LayoutInflater inflater = (LayoutInflater)UpdateProfileActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
   View layout = inflater.inflate(R.layout.list1, null, false);

   final ListView title = (ListView)layout.findViewById(R.id.listview);
 
   final AlertDialog Dial = dialog1.create();
   ArrayAdapter<String> ad=new ArrayAdapter<String>(UpdateProfileActivity.this, android.R.layout.select_dialog_singlechoice,stringList);
   title.setAdapter(ad);
 
   if(Tv_country.getText().toString().equalsIgnoreCase(""))
   {
    Log.d("hello", "finally done if");
   }
   else
   {
    pos=Tv_country.getText().toString();
    int a=stringList.indexOf(pos);
    title.setSelection(a);
    title.setChoiceMode(title.CHOICE_MODE_SINGLE);
    title.setItemChecked(a, true);
   }
   Dial.setView(layout);
   title.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Dial.dismiss();
Tv_country.setText(stringList.get(arg2));
pos=(String) arg0.getItemAtPosition(arg2);
}
});

   Dial.show();


}

else if(v==Imgv_txtclear_fname){
Lay_menufooter.setVisibility(View.GONE);
Tv_first_name.setText("");

}
else if(v==Imgv_txtclear_lname){
Lay_menufooter.setVisibility(View.GONE);
Tv_last_name.setText("");
}
/* else if(v==Imgv_txtclear_email){

Tv_email.setText("");

}*/
else if(v==Imgv_txtclear_phone){
Tv_phone.setText("");
}
else if(v==Imgv_txtclear_address){
Tv_address.setText("");
}
else if(v==Imgv_txtclear_zipcode){
Tv_zip.setText("");
}
else if(v==Imgv_txtclear_city)
{
Tv_city.setText("");
}

else if(v==Imgv_txtclear_country)
{
Tv_country.setText("");
}



else if(v==Btn_submit){


if (firstname.equals("") || lastname.equals("")
|| email.equals("")|| address.equals("")|| zip.equals("")|| city.equals("")
|| country.equals("")|| phone.equals("")) {
if (firstname.equals("")) {
Toast.makeText(UpdateProfileActivity.this, "Please provide first name",
Toast.LENGTH_LONG).show();

}
else if (lastname.equals("")) {
Toast.makeText(UpdateProfileActivity.this, "Please provide last name",
Toast.LENGTH_LONG).show();

}
else if (email.equals("")) {
Toast.makeText(UpdateProfileActivity.this, "Please provide email id",
Toast.LENGTH_LONG).show();

}

else if (!checkEmail(email)) {
Toast.makeText(UpdateProfileActivity.this, "Please provide valid email id",
Toast.LENGTH_LONG).show();
}

else if (address.equals("")) {
Toast.makeText(UpdateProfileActivity.this, "Please provide address",
Toast.LENGTH_LONG).show();

}

else if (zip.equals("")) {
Toast.makeText(UpdateProfileActivity.this, "Please provide zip",
Toast.LENGTH_LONG).show();

}
else if (city.equals("")) {
Toast.makeText(UpdateProfileActivity.this, "Please provide city",
Toast.LENGTH_LONG).show();

}
else if (country.equals("")) {
Toast.makeText(UpdateProfileActivity.this, "Please provide country",
Toast.LENGTH_LONG).show();

}

else if (phone.equals("")) {
Toast.makeText(UpdateProfileActivity.this, "Please provide phone no.",
Toast.LENGTH_LONG).show();

}

/*else if(phone.length()<10) {
               Toast.makeText(UpdateProfileActivity.this," Please provide valid phone no",Toast.LENGTH_SHORT).show();
              // am_checked=0;
           }*/
else if(phone.matches(phonenoStr)==false  ) {
               Toast.makeText(UpdateProfileActivity.this," Please provide numeric value",Toast.LENGTH_SHORT).show();
              // am_checked=0;
           }


}
else if(phone.length()<10||phone.length()>15) {
               Toast.makeText(UpdateProfileActivity.this," Please provide valid phone no",Toast.LENGTH_SHORT).show();
              // am_checked=0;
           }


/*else if (!checkEmail(email)) {
Toast.makeText(UpdateProfileActivity.this, "Please provide valid email id",
Toast.LENGTH_LONG).show();
}*/


else {

callDialog();

}


}


}

private boolean checkEmail(String email) {
   return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
}



}




**********************************************************************************
















package com.rakesht;


import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.rakesht.JSONHandler;
import com.rakesht.json.JSONParserDataActivity;
import com.rakesht.json.MyHttpConnection;

public class ItemActivity extends Activity implements OnClickListener{
    TextView Tv_item_back,Tv_item_header;
    ListView Lv_item;
    ImageLoader imageDownloadNewList;
    String response = "",  getSearch;
    Editor editor;

    private MobileArrayAdapter listAdapter;
    SharedPreferences preferences;
    private ProgressDialog progressDialog;
    private boolean flag_response = false;
    private int selectedOption;
    ImageView Imgv_selected;
    private final ArrayList<JSONParserDataActivity> itemArrayList = new ArrayList<JSONParserDataActivity>();
   
     
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
          setContentView(R.layout.item);
   
    init();
    Imgv_selected=(ImageView)findViewById(Footer.ABOUT_ID);
    Imgv_selected.setImageResource(R.drawable.icon_about_selected);
    }
   
    public void init(){
       
        Lv_item=(ListView)findViewById(R.id.item_listv);
        imageDownloadNewList = new ImageLoader(this);
        preferences = getSharedPreferences("My_Pref", 0);
        editor=preferences.edit();
        selectedOption = getIntent().getIntExtra("from", selectedOption);
        getSearch="http://100.101.130.200/rakesht/json.php?action=getitem&page=1";
        callDialog();
    }
   
    public void callDialog() {
        progressDialog = ProgressDialog.show(itemActivity.this, null, "Loading...");
        progressDialog.setCancelable(true);
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                getData();
            }
        }).start();
    }

    public void getData() {

        response = MyHttpConnection.makeConnection(getSearch);
       
        Log.i("System out","Response : "+response);

        if(response != null){
            flag_response = true;
        }else {
            flag_response = false;
        }
        handler.sendEmptyMessage(0);
    }

    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if (progressDialog != null) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                if (flag_response) {
                    setData();
                }else {
                    Toast.makeText(getApplicationContext(), "No data!", Toast.LENGTH_SHORT).show();
                }
            }
        };
    };

    public void setData() {
        try {
            JSONArray jsonArray;
            JSONObject jsonObject;

            jsonArray = new JSONArray(response);
            for (int i = 0; i < jsonArray.length(); i++) {
                jsonObject = jsonArray.getJSONObject(i);
                itemArrayList.add((JSONParserDataActivity) new JSONHandler().parse(
                        jsonObject.toString(), JSONParserDataActivity.class,
                        "com.rakesh.json"));
            }

            Log.i("System out", "itemname : " + itemArrayList.size()+"\n"+itemArrayList.get(0).getitemName());

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "No item found!", Toast.LENGTH_SHORT).show();
            //itemActivity.this.finish();
        }

        if (itemArrayList.isEmpty()) {
            //Toast.makeText(getApplicationContext(), "No record found!", Toast.LENGTH_SHORT).show();
            //itemActivity.this.finish();
        }else {
            Lv_item=(ListView)findViewById(R.id.item_listv);
            Lv_item.setDivider(getResources().getDrawable(R.drawable.line));
            Lv_item.setCacheColorHint(Color.TRANSPARENT);
            Lv_item.setFocusable(true);
            listAdapter=new MobileArrayAdapter(this, itemArrayList);

           Lv_item.setAdapter( listAdapter );

           Lv_item.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?>parent, View view,int position, long id){

                         editor.putString("itemID", itemArrayList.get(position).getItemId());
                        editor.putString("itemname", itemArrayList.get(position).getItemName());
                        editor.putString("price", itemArrayList.get(position).getPrice());
//                        editor.putString("getItemDescription", itemArrayList.get(position).getItemDescription());
                        editor.commit();
                        Intent i=new Intent(getApplicationContext(),ItemDetailActivity.class);
                        startActivity(i);
                        //itemActivity.this.finish();
                       
                }
            });
        }
    }

   
    public class MobileArrayAdapter extends ArrayAdapter<JSONParserDataActivity> {
        private final Context context;
       

        public MobileArrayAdapter(Context context,ArrayList<JSONParserDataActivity> itemArrayList) {
            super(context, R.layout.item_list_item, itemArrayList);
            this.context = context;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View rowView = inflater.inflate(R.layout.item_list_item, parent,
                    false);
            TextView tvitemname = (TextView) rowView.findViewById(R.id.txt_item_name);
                   
            TextView tvitemdescription = (TextView) rowView.findViewById(R.id.txt_item_description);
            TextView tvitem = (TextView) rowView.findViewById(R.id.tv_item_rent);
            ImageView imgvitemimage=(ImageView)rowView.findViewById(R.id.imageView_item);   
           
            try {
               
                imageDownloadNewList.DisplayImage(getString(R.string.url_image_item)+
                        itemArrayList.get(position)
                        .getItemImage()
                        .replace(" ", "%20"),imgvitemlimage);
                tvitemname.setText(itemArrayList.get(position).getItemName());
                tvitemdescription.setText(itemArrayList.get(position).getItemDescription());
                tvitem.setText(itemArrayList.get(position).getPrice());
               
               
            } catch (Exception e)
            {
                // TODO: handle exception
                e.printStackTrace();
                //Toast.makeText(getApplicationContext(), "No record found!", Toast.LENGTH_SHORT).show();
                //itemActivity.this.finish();
            }
           
           

            return rowView;
        }
    }







    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
       
    }
   
   
   

}

*********************************************************************************

ItemDetail.java


package com.rakesht;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Rect;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Parcelable;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.rakesht.R.layout;
import com.rakesht.fb.DialogError;
import com.rakesht.fb.Facebook;
import com.rakesht.fb.Facebook.DialogListener;
import com.rakesht.fb.FacebookError;
import com.rakesht.fb.FbLoginCommon;
import com.rakesht.json.JSONHandler;
import com.rakesht.json.JSONParserDataActivity;
import com.rakesht.json.MyHttpConnection;
import com.rakesht.json.RoomDetails;
import com.rakesht.json.Share;
import com.rakesht.quickaction.ActionItem;
import com.rakesht.quickaction.QuickAction;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.PlusShare;



public class itemDetailActivity extends Activity implements OnClickListener,
PlusClient.ConnectionCallbacks, PlusClient.OnConnectionFailedListener,
DialogInterface.OnCancelListener
{

QuickAction mQuickAction;
ActionItem addAction, accAction, upAction,ueeAction;
TextView Tv_items_back,Tv_itemdetail_header,Tv_itemname,Tv_item_description,Tv_item_location,Tv_room_price,
Tv_checkindate,Tv_month,Tv_date,Tv_comletedate,Tv_checkoutdate,Tv_month_checkout,Tv_date_checkout,
Tv_comletedate_checkout,Tv_complete_date_checkout,Tv_spinner1,Tv_spinner2,Tv_spinner3,Tv_value,Tv_noofnights,totalperson,
Tv_itemlocation,Tv_checkindate1,Tv_checkoutdate1;
ImageView Imgv_itemsdetail_socialshring,Imgv_itemimage,Imgv_itemi_locationicon,
Imgv_spinner1,Imgv_spinner2,Imgv_spinner3,Imgv_plussign,Imgv_minussign;
Button Btn_select_rooms;
Intent i;
int item;
DatePickerDialog dp;
private String price;
Calendar c = Calendar.getInstance();
private final ArrayList<RoomDetails> itemArrayList1 = new ArrayList<RoomDetails>();
private final ArrayList<RoomDetails> itemArrayList = new ArrayList<RoomDetails>();
int m,d,y;
Double latitude,longitude;
private int counter=0,date;
private String stringVal;
private String stringdate;
StringBuilder strReturnedAddress;
JSONParserDataActivity jsonParserData;
ImageLoader imageDownloadNewList;
String response = "",  getSearch,response1="";
SharedPreferences preferences;
private int selectedOption;
ImageView Imgv_selected;
private String desc;
protected String extStorageDirectory;
protected File outputFile;
protected Bitmap bm;
protected static final String TAG = "ShareActivity";
private static final String STATE_SHARING = "state_sharing";
private static final int DIALOG_GET_GOOGLE_PLAY_SERVICES = 1;
private static final int REQUEST_CODE_SIGN_IN = 1;
private static final int REQUEST_CODE_INTERACTIVE_POST = 2;
private static final int REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES = 3;
private static final String LABEL_VIEW_ITEM = "VIEW_ITEM";
private boolean mSharing;
private PlusClient mPlusClient;
private Facebook facebook = new Facebook("194678594056909");
Date Bookdate;

String[] numbers = new String[] { " ","1",
"2", "3",
"4", "5",
"6" ,"7","8","9","10"};
private int year;
private int month;
private int day;
private SharedPreferences settings;
private Editor editor;
private LinearLayout lladdMenu;
private LayoutInflater Searchinflater;
private ImageView mailshare,fbshare,twittershare,gplushshare;
private Animation anim;
static final int DATE_PICKER_ID = 1111;
static final int DATE_PICKER_ID_OUT = 1121;
public static boolean isMenuVisible = false;
boolean flag,spin1=false, spin2=false, spin3=false;
String itemID,itemName,getitemImage,cindate,itemname,nights,cout;
private Date inate;
private ProgressDialog progressDialog;
private boolean flag_response=false,flag_response1=false;
Date currentDate,datePickerDate;
String[] nameOfAppsToShareWith = new String[] { "Email", "Yahoo", "gmail" };
String[] blacklist = new String[]{"Facebook", "Twitter", "Bluetooth", "Google+", "Picasa"};
ArrayList<Share> shareArray=new ArrayList<Share>();
private PopupWindow mWindow_color;
private Display display;
ScrollView lay_item_detail;
private int mYear;
   private int mMonth;
   private int mDay;
   private int mHour;
   private int mMinute;
boolean showing=true;
 
@Override
public void onStart()
{
       super.onStart();
       App.activity1 = itemsDetailActivity.this;
}

@Override
public void onDestroy()
{

       super.onDestroy();
//        App.activity1 = null;
}



public void initiatePopupWindow() {
try {
//

Searchinflater = (LayoutInflater)itemsDetailActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View   MenuView = Searchinflater.inflate(R.layout.quickaction_new, null, true);


mailshare = (ImageView)MenuView.findViewById(R.id.mailshare);
fbshare= (ImageView)MenuView.findViewById(R.id.fbshare);
twittershare = (ImageView)MenuView.findViewById(R.id.twittershare);
gplushshare= (ImageView)MenuView.findViewById(R.id.gplushshare);

mailshare.setOnClickListener(new OnClickListener()
{
private File cacheDir;
private List<ResolveInfo> emailers;
private ListView spnEmailProgram;
private Intent mail,chooser;

@Override
public void onClick(View v)
{
flag = false;
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent)
{
try {

BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
bm = LoadImage(getString(R.string.url_image_items)+getitemImage, bmOptions);

if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"ExM");
   else
       cacheDir=getCacheDir();

   if(!cacheDir.exists())
       cacheDir.mkdirs();

           OutputStream outStream = null;
outputFile = new File(cacheDir, "image.PNG");
outStream = new FileOutputStream(outputFile);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();

} catch (Exception e) {
e.printStackTrace();
}

Intent sendIntent = new Intent(Intent.ACTION_SEND);
String[] recipients={"testlast11@gmail.com"};
sendIntent.putExtra(Intent.EXTRA_EMAIL, recipients);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name).replace("{itemName}", itemname));
sendIntent.putExtra(Intent.EXTRA_TEXT   , shareArray.get(0).getSettings_value());
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(outputFile));
sendIntent.setType("message/rfc822");
startActivity(Intent.createChooser(sendIntent, "Send mail"));

}
else
{
try {

BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
bm = LoadImage(getString(R.string.url_image_items)+getitemImage, bmOptions);

if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"ExM");
   else
       cacheDir=getCacheDir();

   if(!cacheDir.exists())
       cacheDir.mkdirs();

           OutputStream outStream = null;
outputFile = new File(cacheDir, "image.PNG");
outStream = new FileOutputStream(outputFile);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();

} catch (Exception e) {
e.printStackTrace();
}

Intent sendIntent = new Intent(Intent.ACTION_SEND);
String[] recipients={"testlast11@gmail.com"};
sendIntent.putExtra(Intent.EXTRA_EMAIL, recipients);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name).replace("{itemName}", itemname));
sendIntent.putExtra(Intent.EXTRA_TEXT   , shareArray.get(0).getSettings_value());
sendIntent.setType("message/rfc822");
startActivity(Intent.createChooser(sendIntent, "Send mail"));
}


mWindow_color.dismiss();

Log.d("src", "remove view value..."+flag);

}
});
fbshare.setOnClickListener(new OnClickListener()
{

@SuppressLint("ParserError")
@Override
public void onClick(View v)
{
flag = false;
Log.d("src", "fb share value...");

postOnWall(getString(R.string.url_image_items)+ getitemImage+"");
Log.d("src", "remove view value..."+flag);

mWindow_color.dismiss();

}
});
twittershare.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
flag = false;
String urlTwitter = "https://twitter.com/share?text=" + shareArray.get(3).getSettings_value().replace("{itemName}", itemname);
Intent twitt = new Intent(itemsDetailActivity.this,TwitterDialog.class);
twitt.putExtra("twturl", "" + urlTwitter);
twitt.putExtra("title", "Twitter");
startActivity(twitt);
Log.d("src", "remove view value..."+flag);
mWindow_color.dismiss();


}
});
gplushshare.setOnClickListener(new OnClickListener()
{

@Override
public void onClick(View v)
{
flag = false;
if (!mPlusClient.isConnected())
{

mSharing = true;

if (!mPlusClient.isConnecting())
{
mPlusClient.connect();
}
} else {
startActivityForResult(getInteractivePostIntent(),
REQUEST_CODE_INTERACTIVE_POST);
}

Log.d("src", "remove view value..."+flag);
mWindow_color.dismiss();

}
});

int xPos, yPos, arrowPos;

int[] location = new int[2];

Imgv_itemsdetail_socialshring.getLocationOnScreen(location);

Rect anchorRect = new Rect(location[0], location[1], location[0]
                                                             + Imgv_itemsdetail_socialshring.getWidth(), location[1] + Imgv_itemsdetail_socialshring.getHeight());

int rootHeight = MenuView.getMeasuredHeight();
int rootWidth = MenuView.getMeasuredWidth();

if (rootWidth == 0) {
rootWidth = MenuView.getMeasuredWidth();
}

int screenWidth = display.getWidth();
int screenHeight = display.getHeight();

// automatically get X coord of popup (top left)

if ((anchorRect.left + rootWidth) > screenWidth) {
xPos = anchorRect.left - (rootWidth - Imgv_itemsdetail_socialshring.getWidth());
xPos = (xPos < 0) ? 0 : xPos;

arrowPos = anchorRect.centerX() - xPos;

} else {
if (Imgv_itemsdetail_socialshring.getWidth() > rootWidth) {
xPos = anchorRect.centerX() - (rootWidth / 2);
} else {
xPos = anchorRect.left;
}

arrowPos = anchorRect.centerX() - xPos;
}

int dyTop = anchorRect.top;
int dyBottom = screenHeight - anchorRect.bottom;

boolean onTop = (dyTop > dyBottom) ? true : false;

if (onTop) {
if (rootHeight > dyTop) {
yPos = 15;
} else {
yPos = anchorRect.top - rootHeight;
}
} else {
yPos = anchorRect.bottom;
}

//yPos=(display.getHeight()*50)/100;

mWindow_color = new PopupWindow(MenuView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT/*(screenHeight*75)/100*/, false);
mWindow_color.setOutsideTouchable(true);
mWindow_color.showAtLocation(Imgv_itemsdetail_socialshring, Gravity.NO_GRAVITY, xPos-80, yPos);

} catch (Exception e) {
e.printStackTrace();
}
}

@Override
protected void onRestart()
{
super.onRestart();
if(cindate.equalsIgnoreCase(""))
{
//Log.d("date", "date======>if"+cindate);
}
else
{
String[] dtarray=cindate.split(" ");
String[] night=nights.split(",");
String[] outd=cout.split(" ");
SimpleDateFormat format11 = new SimpleDateFormat("MMM");
        SimpleDateFormat format21 = new SimpleDateFormat("MMMM");
        String monthname1="", outmonth="";
        try
{
monthname1 = format21.format(format11.parse(dtarray[2]));
outmonth=format21.format(format11.parse(outd[2]));
}
        catch (Exception e)
        {

}

Tv_comletedate.setText(dtarray[1]+" "+monthname1+" "+dtarray[3]);
Tv_date.setText(dtarray[1]);
Tv_complete_date_checkout.setText(outd[1]);
Tv_comletedate_checkout.setText(outmonth+" "+outd[3]);
Tv_date_checkout.setText(outd[1]);
counter=Integer.parseInt(night[0]);
Tv_value.setText(night[0]);
Tv_noofnights.setText(night[0]);



SimpleDateFormat format1 = new SimpleDateFormat("MMM");
        SimpleDateFormat format2 = new SimpleDateFormat("MM");
        String monthname="";
        int m=0;
        try
{
monthname = format2.format(format1.parse(outd[2]));
m=Integer.parseInt(monthname);

if(m>0)
{
m=m-1;
}
}
catch (ParseException e)
{
e.printStackTrace();
}
c.set(Integer.parseInt(outd[3]), m, Integer.parseInt(outd[1]));
year  = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day   = c.get(Calendar.DAY_OF_MONTH);
}

}

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.itemdetail1);
settings = getSharedPreferences("My_Pref", 0);
editor=settings.edit();
display = getWindowManager().getDefaultDisplay();
itemID=settings.getString("itemID", "");
cindate=settings.getString("cindate", "");
nights=settings.getString("nights", "");
cout=settings.getString("cout", "");
itemname=settings.getString("itemname", "");
price=settings.getString("price", "");
lay_item_detail=(ScrollView)findViewById(R.id.lay_item_detail);
init();
if(cindate.equalsIgnoreCase(""))
{
//Log.d("date", "date======>if"+cindate);
}
else
{
String[] dtarray=cindate.split(" ");
String[] night=nights.split(",");
String[] outd=cout.split(" ");
SimpleDateFormat format11 = new SimpleDateFormat("MMM");
        SimpleDateFormat format21 = new SimpleDateFormat("MMMM");
        String monthname1="", outmonth="";
        try
{
monthname1 = format21.format(format11.parse(dtarray[2]));
outmonth=format21.format(format11.parse(outd[2]));
}
        catch (Exception e)
        {

}

Tv_comletedate.setText(dtarray[1]+" "+monthname1+" "+dtarray[3]);
Tv_date.setText(dtarray[1]);
Tv_complete_date_checkout.setText(outd[1]);
Tv_comletedate_checkout.setText(outmonth+" "+outd[3]);
Tv_date_checkout.setText(outd[1]);
counter=Integer.parseInt(night[0]);
Tv_value.setText(night[0]);
Tv_noofnights.setText(night[0]);



SimpleDateFormat format1 = new SimpleDateFormat("MMM");
        SimpleDateFormat format2 = new SimpleDateFormat("MM");
        String monthname="";
        int m=0;
        try
{
monthname = format2.format(format1.parse(outd[2]));
m=Integer.parseInt(monthname);

if(m>0)
{
m=m-1;
}
}
catch (ParseException e)
{
e.printStackTrace();
}
c.set(Integer.parseInt(outd[3]), m, Integer.parseInt(outd[1]));
mYear  = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay   = c.get(Calendar.DAY_OF_MONTH);
}

preferences = getSharedPreferences("My_Pref", 0);

mPlusClient = new PlusClient.Builder(this, this, this).build();
mSharing = savedInstanceState != null
&& savedInstanceState.getBoolean(STATE_SHARING, false);
int available = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (available != ConnectionResult.SUCCESS) {
showDialog(DIALOG_GET_GOOGLE_PLAY_SERVICES);
}

Imgv_selected=(ImageView)findViewById(Footer.ABOUT_ID);
Imgv_selected.setImageResource(R.drawable.icon_about_selected);

lladdMenu = (LinearLayout) findViewById(R.id.addMenu_my_prfl);

Imgv_itemsdetail_socialshring.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Log.d("src", "share button value...");

if(showing)
{
initiatePopupWindow();
showing=false;
}
else
{
mWindow_color.dismiss();
showing=true;
}
}
});

final Calendar c = Calendar.getInstance();
       mYear = c.get(Calendar.YEAR);
       mMonth = c.get(Calendar.MONTH);
       mDay = c.get(Calendar.DAY_OF_MONTH);
   
     
       lay_item_detail.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("dg", "out sideeeeee");

if(showing){
Log.d("dg", "in ifffff");
}else
{
Log.d("dg", "in elseeeee");
mWindow_color.dismiss();
showing=true;
}
return false;
}
});
}




public void callDialog()
{
progressDialog = ProgressDialog.show(itemsDetailActivity.this, null, "Loading...");
progressDialog.setCancelable(true);
new Thread(new Runnable() {

@Override
public void run()
{
getData();
}
}).start();
}
protected void getData()
{
getSearch="http://100.101.130.200/rakesht/json.php?action=getitemDetail&itemId="+itemID;
String share="http://100.101.130.200/rakesht/json.php?action=getitemShare";
response = MyHttpConnection.makeConnection(getSearch);
response1 = MyHttpConnection.makeConnection(share);

Log.i("System out","Response : "+response);

if(response != null)
{
flag_response = true;
}
else
{
flag_response = false;
}


if(response1 != null)
{
flag_response1 = true;
}else {
flag_response1 = false;
}
handler.sendEmptyMessage(0);

}

Handler handler = new Handler()
{
public void handleMessage(android.os.Message msg) {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (flag_response) {
setData();
}else {
Toast.makeText(getApplicationContext(), "No data!", Toast.LENGTH_SHORT).show();
}


if(flag_response1)
{
ShareDataGet();
}
}
};
};
private TextView txtheaderclose;
protected void ShareDataGet()
{
//shareArray
JSONArray jsonArray;
JSONObject jsonObject;



try
{
jsonArray = new JSONArray(response1);
jsonObject = jsonArray.getJSONObject(0);

for (int i = 0; i < jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
shareArray.add((Share) new JSONHandler().parse(jsonObject.toString(), Share.class,"com.rakesht.json"));
}
}
catch (Exception e)
{
e.printStackTrace();
}


}


public void setData()
{

try {
JSONArray jsonArray;
JSONObject jsonObject;

jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
itemArrayList.add((RoomDetails) new JSONHandler().parse(
jsonObject.toString(), RoomDetails.class,
"com.rakesht.json"));

getitemImage=itemArrayList.get(i).getitemImage();
desc=itemArrayList.get(i).getitemDescription();
JSONArray jsonArray1;
JSONObject jsonObject1;
String rooms = itemArrayList.get(0).getRooms();
jsonArray1 = new JSONArray(rooms);
for (int h = 0; h < jsonArray1.length(); h++)
{
jsonObject1 = jsonArray1.getJSONObject(h);
itemArrayList1.add((RoomDetails) new JSONHandler().parse(jsonObject1.toString(), RoomDetails.class,"com.rakesht.json"));
}


}


imageDownloadNewList = new ImageLoader(this);

Tv_itemname.setText(itemArrayList.get(0).getitemName());
Log.i("System out", "item name : " + itemArrayList.size()+"\n"+itemArrayList.get(0).getitemName());
Tv_item_description.setText(itemArrayList.get(0).getitemDescription());
Log.i("System out", "item name : " + itemArrayList.size()+"\n"+itemArrayList.get(0).getitemName());
Tv_room_price.setText("US$ "+price);
Log.i("System out", "item name : " + itemArrayList.size()+"\n"+itemArrayList.get(0).getitemName());
Tv_itemlocation.setText(itemArrayList.get(0).getitemAddress()+", "+itemArrayList.get(0).getitemCity()+", "+itemArrayList.get(0).getitemState());

imageDownloadNewList.DisplayImage(getString(R.string.url_image_items)+
itemArrayList.get(0).getitemImage().replace(" ", "%20"),Imgv_itemimage);
Tv_checkindate1.setText(itemArrayList.get(0).getitemCheckinTime());
Tv_checkoutdate1.setText(itemArrayList.get(0).getitemCheckoutTime());
Log.i("System out", "item name : " + itemArrayList.size()+"\n"+itemArrayList.get(0).getitemName());


editor.putString("itemname",itemArrayList.get(0).getitemName());
editor.putString("cintime",itemArrayList.get(0).getitemCheckinTime() );
editor.putString("couttime",itemArrayList.get(0).getitemCheckoutTime() );
editor.putString("internetfacility",itemArrayList1.get(0).getHrFaciltiy());
editor.putString("itemImage",itemArrayList1.get(0).getitemImage());
editor.commit();

Log.i("System out","item name--1> : "+itemArrayList.get(0).getitemName());
Log.i("System out","Check in time---1> : "+itemArrayList.get(0).getitemCheckinTime());
Log.i("System out","check out time---1> : "+itemArrayList.get(0).getitemCheckoutTime());
Log.i("System out","item facility---1> : "+itemArrayList1.get(0).getHrFaciltiy());




} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "No record found!", Toast.LENGTH_SHORT).show();
itemsDetailActivity.this.finish();
}
}

private Animation inFromTopAnimation()
{
Animation inFromTop = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, -1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);

inFromTop.setDuration(200);
inFromTop.setInterpolator(new AccelerateInterpolator());

return inFromTop;
}

private Animation outToTopAnimation() {

Animation outtoTop = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f);
outtoTop.setDuration(100);
outtoTop.setInterpolator(new AccelerateInterpolator());

return outtoTop;

}
@SuppressLint("ParserError")
public void init(){

Tv_items_back=(TextView)findViewById(R.id.back);
txtheaderclose=(TextView)findViewById(R.id.txtheaderclose);
// txtheaderclose.setBackgroundResource(R.drawable.location_icon_2x);
txtheaderclose.setVisibility(View.VISIBLE);
txtheaderclose.setText("Map");
Tv_itemdetail_header=(TextView)findViewById(R.id.txtheaderResTitle);
Imgv_itemsdetail_socialshring=(ImageView)findViewById(R.id.imv_socialsharing_itemsdetail);
Btn_select_rooms=(Button)findViewById(R.id.btn_select_rooms);
Imgv_itemimage=(ImageView)findViewById(R.id.imageView_itemdetail);
Tv_itemname=(TextView)findViewById(R.id.txtv_itemdetail_name);
Tv_item_description=(TextView)findViewById(R.id.txt_itemdetail_description);
Tv_item_location=(TextView)findViewById(R.id.tv_item_location);
Tv_room_price=(TextView)findViewById(R.id.tv_roomprice);
Tv_itemlocation=(TextView)findViewById(R.id.tv_item_location);
Imgv_itemi_locationicon=(ImageView)findViewById(R.id.imgv_item_locationicon);
Tv_checkindate=(TextView)findViewById(R.id.tv_checkindate);
Tv_checkoutdate=(TextView)findViewById(R.id.tv_checkoutdate);
Tv_month=(TextView)findViewById(R.id.tv_month);
Tv_date=(TextView)findViewById(R.id.tv_date);
Tv_comletedate=(TextView)findViewById(R.id.tv_complete_date);
Tv_month_checkout=(TextView)findViewById(R.id.tv_month_checkout);
Tv_date_checkout=(TextView)findViewById(R.id.tv_date_checkout);
Tv_comletedate_checkout=(TextView)findViewById(R.id.tv_complete_date_checkout);
Tv_complete_date_checkout=(TextView)findViewById(R.id.tv_complete_day_checkout);
Tv_spinner1=(TextView)findViewById(R.id.tv_spinner1);
Tv_spinner2=(TextView)findViewById(R.id.tv_spinner2);
Tv_spinner3=(TextView)findViewById(R.id.tv_spinner3);
Imgv_spinner1=(ImageView)findViewById(R.id.imgv_spinner1);
Imgv_spinner2=(ImageView)findViewById(R.id.imgv_spinner2);
Imgv_spinner3=(ImageView)findViewById(R.id.imgv_spinner3);
Imgv_plussign=(ImageView)findViewById(R.id.imgv_plus);
Imgv_minussign=(ImageView)findViewById(R.id.imgv_minus);
Tv_value=(TextView)findViewById(R.id.tv_value);
Tv_noofnights=(TextView)findViewById(R.id.tv_noofnights);
Tv_checkoutdate1=(TextView)findViewById(R.id.cout);
Tv_checkindate1=(TextView)findViewById(R.id.cin);

// mailshare.setOnClickListener(this);
// fbshare.setOnClickListener(this);
// twittershare.setOnClickListener(this);
// gplushshare.setOnClickListener(this);
Tv_spinner1.setOnClickListener(this);
Tv_spinner2.setOnClickListener(this);
Tv_spinner3.setOnClickListener(this);
Imgv_spinner1.setOnClickListener(this);
Imgv_spinner2.setOnClickListener(this);
Imgv_spinner3.setOnClickListener(this);
Tv_items_back.setOnClickListener(this);
Btn_select_rooms.setOnClickListener(this);
Imgv_itemsdetail_socialshring.setOnClickListener(this);
Imgv_plussign.setOnClickListener(this);
Imgv_minussign.setOnClickListener(this);
Tv_itemdetail_header.setText("items Detail");
Tv_item_description.setOnClickListener(this);
txtheaderclose.setOnClickListener(this);
//--------------------------------------------------------------------------------qick action

addAction = new ActionItem();
addAction.setIcon1(getResources().getDrawable(R.drawable.fb_icon_share));
addAction.setIcon(getResources().getDrawable(R.drawable.email_icon_share));

accAction = new ActionItem();
accAction.setIcon1(getResources().getDrawable(R.drawable.twitter_icon_share));
accAction.setIcon(getResources().getDrawable(R.drawable.gpluse_icon_share));

mQuickAction = new QuickAction(this, QuickAction.VERTICAL);
mQuickAction.addActionItem(addAction);
mQuickAction.addActionItem(accAction);

//------------------------------------------------------------------------------------------------data parsing

imageDownloadNewList = new ImageLoader(this);

Tv_checkindate.setOnClickListener(this);
Tv_month.setOnClickListener(this);
Tv_date.setOnClickListener(this);
Tv_comletedate.setOnClickListener(this);
Tv_checkoutdate.setOnClickListener(this);
Tv_month_checkout.setOnClickListener(this);
Tv_date_checkout.setOnClickListener(this);
Tv_comletedate_checkout.setOnClickListener(this);

year  = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day   = c.get(Calendar.DAY_OF_MONTH);

m=month;
d=day;
y=year;

// Show current date

SimpleDateFormat format1 = new SimpleDateFormat("MM");
SimpleDateFormat format2 = new SimpleDateFormat("MMMM");
String monthname = null ;
try
{
monthname = format2.format(format1.parse(""+(month + 1)));
}
catch (ParseException e)
{
e.printStackTrace();
}
System.out.println(monthname);

Tv_comletedate.setText(new StringBuilder().append(day).append(" ").append(monthname).append(" ").append(year).append(" "));

Tv_month.setText(new StringBuilder().append(monthname).append(" "));
Tv_date.setText(new StringBuilder().append(day).append(" "));


Tv_comletedate_checkout.setText(new StringBuilder().append(monthname).append(" ").append(year).append(" "));
Tv_complete_date_checkout.setText(new StringBuilder().append(day).append(" "));
Tv_month_checkout.setText(new StringBuilder().append(monthname).append(" "));
Tv_date_checkout.setText(new StringBuilder().append(day).append(" "));
Tv_comletedate_checkout.setText(new StringBuilder().append(monthname).append(" ").append(year).append(" "));
Tv_complete_date_checkout.setText(new StringBuilder().append(day).append(" "));
Tv_month_checkout.setText(new StringBuilder().append(monthname).append(" "));
Tv_date_checkout.setText(new StringBuilder().append(day).append(" "));

callDialog();
}



/*protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DATE_PICKER_ID:
return new DatePickerDialog(this, pickerListener, year, month,day);
}
return null;
}*/

private final DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener()
{
private String convertedDate;

@SuppressWarnings("deprecation")
@SuppressLint("SimpleDateFormat")
@Override
// public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay)
// {
//
// Log.d("date", "sel date===>"+selectedYear+"....... "+selectedMonth+"...."+selectedDay);


// onDateSet method
public void onDateSet(DatePicker view, int year1, int monthOfYear,
int dayOfMonth) {

mYear = year1;
           mMonth = monthOfYear;
           mDay = dayOfMonth;

Date currentDate = new Date();

Date date = new Date(year1 - 1900, monthOfYear, dayOfMonth);

//
// date.setHours(currentDate.getHours());
// date.setMinutes(currentDate.getMinutes());
// date.setSeconds(currentDate.getSeconds());

Log.d("System out", "True: Current date: "+currentDate +"  Selected date: "+date);


if (removeTime(date).equals(removeTime(currentDate)))
{
SimpleDateFormat format1 = new SimpleDateFormat("MM");
SimpleDateFormat format2 = new SimpleDateFormat("MMMM");
String monthname = null ;
try
{
monthname = format2.format(format1.parse(""+(monthOfYear + 1)));
}
catch (ParseException e)
{
e.printStackTrace();
}
System.out.println(monthname);

Tv_comletedate.setText(new StringBuilder()
.append(dayOfMonth).append(" ")
.append(monthname)
.append(" ").append(year1)
.append(" "));
Tv_month.setText(new StringBuilder().append(monthname).append(" "));
Tv_date.setText(new StringBuilder().append(dayOfMonth).append(" "));

Tv_comletedate_checkout.setText(new StringBuilder()
.append(monthname)
.append(" ").append(year1)
.append(" "));

Tv_complete_date_checkout.setText(new StringBuilder().append(dayOfMonth).append(" "));
Tv_month_checkout.setText(new StringBuilder().append(monthname).append(" "));

Tv_date_checkout.setText(new StringBuilder().append(dayOfMonth).append(" "));

counter=0;
Tv_value.setText("0");
Tv_noofnights.setText("0");
Tv_date_checkout.setText(dayOfMonth+"");
Tv_complete_date_checkout.setText(dayOfMonth+"");
Tv_month_checkout.setText(monthname+"");
Tv_comletedate_checkout.setText(monthname+" "+year1);
c.set(year, month, day);
}

else if(date.after(currentDate))
{
Log.d("System out", "iffffffffffffffff");
try {
DateFormat df1 = new SimpleDateFormat("dd MM yyyy", Locale.ENGLISH);
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

convertedDate = df2.format(df1.parse(mDay+" "+(mMonth + 1)+" "+mYear));

}
catch (ParseException e) {
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();

year  = year1;
month = monthOfYear;
day   = dayOfMonth;


SimpleDateFormat format1 = new SimpleDateFormat("MM");
SimpleDateFormat format2 = new SimpleDateFormat("MMMM");
String monthname = null ;
try
{
monthname = format2.format(format1.parse(""+(monthOfYear + 1)));
}
catch (ParseException e)
{
e.printStackTrace();
}
System.out.println(monthname);

Tv_comletedate.setText(new StringBuilder()
.append(dayOfMonth).append(" ")
.append(monthname)
.append(" ").append(year1)
.append(" "));
Tv_month.setText(new StringBuilder().append(monthname).append(" "));
Tv_date.setText(new StringBuilder().append(dayOfMonth).append(" "));

Tv_comletedate_checkout.setText(new StringBuilder()
.append(monthname)
.append(" ").append(year1)
.append(" "));

Tv_complete_date_checkout.setText(new StringBuilder().append(dayOfMonth).append(" "));
Tv_month_checkout.setText(new StringBuilder().append(monthname).append(" "));

Tv_date_checkout.setText(new StringBuilder().append(dayOfMonth).append(" "));

counter=0;
Tv_value.setText("0");
Tv_noofnights.setText("0");
Tv_date_checkout.setText(dayOfMonth+"");
Tv_complete_date_checkout.setText(dayOfMonth+"");
Tv_month_checkout.setText(monthname+"");
Tv_comletedate_checkout.setText(monthname+" "+year1);
c.set(year, month, day);


              // updateDisplay();
}else{
Toast.makeText(getApplicationContext(), "kindly select a valid date", Toast.LENGTH_LONG).show();
convertedDate = "";
//updateDisplay();
//showDialog(DATE_DIALOG_ID);
}
}
};



public Date removeTime(Date date) {  
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);
   cal.set(Calendar.HOUR_OF_DAY, 0);
   cal.set(Calendar.MINUTE, 0);
   cal.set(Calendar.SECOND, 0);
   cal.set(Calendar.MILLISECOND, 0);
   return cal.getTime();
}









// Date datePickerDate=new Date(selectedMonth,selectedDay,selectedYear);
// Date currentDate = new Date(m,d,y);
// Date curDate = new Date();
//
// datePickerDate.setYear(selectedYear-1900);
// datePickerDate.setMonth(selectedMonth);
// datePickerDate.setDate(selectedDay);
//
// Date datePickerDate1,curDate1;
// if(datePickerDate.getDate()==curDate.getDate() && datePickerDate.getMonth()==curDate.getMonth() && datePickerDate.getYear()==curDate.getYear())
// {
// datePickerDate.setHours(curDate.getHours());
// datePickerDate.setMinutes(curDate.getMinutes());
// datePickerDate.setSeconds(curDate.getSeconds());
// }
//Fri Jan 31 11:05:26 GMT+05:30 2014

// Date date,date1;
// String convertedTime,convertedTime1;
// try {
//
// SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MM-yyyy");
// SimpleDateFormat parseFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
// date = parseFormat.parse(datePickerDate.toString());
// convertedTime = displayFormat.format(date);
//
// date1 = parseFormat.parse(curDate.toString());
// convertedTime1 = displayFormat.format(date);
//
// SimpleDateFormat format1=new SimpleDateFormat("dd-MM-yyyy");
// datePickerDate=format1.parse(convertedTime);
// curDate=format1.parse(convertedTime1);
// Log.d("date", "date change===>"+datePickerDate+"....... "+curDate);
//
// } catch (ParseException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }  
//

// Log.d("date", "date to check for past===>"+datePickerDate+"....... "+curDate);
//
//
// if(curDate.before(datePickerDate))
// {
// Toast.makeText(itemsDetailActivity.this, "You can not select Past Date", Toast.LENGTH_LONG).show();
// Log.d("date", "date to check if else===>"+datePickerDate+"....... "+curDate);
// }
// else
// {
//// year  = selectedYear;
//// month = selectedMonth;
//// day   = selectedDay;
// Log.d("date", "date to check else===>"+datePickerDate+"....... "+curDate);
//
// SimpleDateFormat format1 = new SimpleDateFormat("MM");
// SimpleDateFormat format2 = new SimpleDateFormat("MMMM");
// String monthname = null ;
// try
// {
// monthname = format2.format(format1.parse(""+(selectedMonth + 1)));
// }
// catch (ParseException e)
// {
// e.printStackTrace();
// }
// System.out.println(monthname);
//
// Tv_comletedate.setText(new StringBuilder()
// .append(selectedDay).append(" ")
// .append(monthname)
// .append(" ").append(selectedYear)
// .append(" "));
// Tv_month.setText(new StringBuilder().append(monthname).append(" "));
// Tv_date.setText(new StringBuilder().append(selectedDay).append(" "));
//
// Tv_comletedate_checkout.setText(new StringBuilder()
// .append(monthname)
// .append(" ").append(selectedYear)
// .append(" "));
//
// Tv_complete_date_checkout.setText(new StringBuilder().append(selectedDay).append(" "));
// Tv_month_checkout.setText(new StringBuilder().append(monthname).append(" "));
//
// Tv_date_checkout.setText(new StringBuilder().append(selectedDay).append(" "));
//
// counter=0;
// Tv_value.setText("0");
// Tv_noofnights.setText("0");
// Tv_date_checkout.setText(selectedDay+"");
// Tv_complete_date_checkout.setText(selectedDay+"");
// Tv_month_checkout.setText(monthname+"");
// Tv_comletedate_checkout.setText(monthname+" "+selectedYear);
// }
//

//c.set(year, month, day);
//dp.updateDate(y, m, d);

//
//Log.d("date", "date to check for past===>"+datePickerDate+"....... "+curDate);
//
// //if (datePickerDate.before(curDate))
// //&& curDate.getDate()!=(datePickerDate.getDate()) && curDate.getMonth()!=(datePickerDate.getMonth()) && curDate.getYear()!=(datePickerDate.getYear())
// Calendar cur=Calendar.getInstance();
// cur.set(y, m, d);
//
// Calendar update1=Calendar.getInstance();
// update1.set(selectedDay, selectedMonth, selectedDay);
//
// datePickerDate=new Date(update1.MONTH,update1.DAY_OF_MONTH,update1.YEAR);
// Date curDate=new Date(cur.MONTH,cur.DAY_OF_MONTH,cur.YEAR);
//
// Log.d("date", "date to check for past===>"+datePickerDate+"....... "+curDate);

// if(datePickerDate.after(currentDate))
// {
// year  = selectedYear;
// month = selectedMonth;
// day   = selectedDay;
//
// SimpleDateFormat format1 = new SimpleDateFormat("MM");
// SimpleDateFormat format2 = new SimpleDateFormat("MMMM");
// String monthname = null ;
// try
// {
// monthname = format2.format(format1.parse(""+(month + 1)));
// }
// catch (ParseException e)
// {
// e.printStackTrace();
// }
// System.out.println(monthname);
//
// Tv_comletedate.setText(new StringBuilder()
// .append(day).append(" ")
// .append(monthname)
// .append(" ").append(year)
// .append(" "));
// Tv_month.setText(new StringBuilder().append(monthname).append(" "));
// Tv_date.setText(new StringBuilder().append(day).append(" "));
//
// Tv_comletedate_checkout.setText(new StringBuilder()
// .append(monthname)
// .append(" ").append(year)
// .append(" "));
//
// Tv_complete_date_checkout.setText(new StringBuilder().append(day).append(" "));
// Tv_month_checkout.setText(new StringBuilder().append(monthname).append(" "));
//
// Tv_date_checkout.setText(new StringBuilder().append(day).append(" "));
//
// counter=0;
// Tv_value.setText("0");
// Tv_noofnights.setText("0");
// Tv_date_checkout.setText(day+"");
// Tv_complete_date_checkout.setText(day+"");
// Tv_month_checkout.setText(monthname+"");
// Tv_comletedate_checkout.setText(monthname+" "+year);
// c.set(year, month, day);
// dp.updateDate(y, m, d);
// }

// else
// {
// Toast.makeText(itemsDetailActivity.this, "You can not select Past Date", Toast.LENGTH_LONG).show();
// dp.updateDate(y, m, d);}

@SuppressLint("NewApi")
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(v==Tv_items_back)
{
itemsDetailActivity.this.finish();
}
/*else if(v==Tv_map)
{
i=new Intent(this,MapActivity.class);
startActivity(i);
}*/

else if(v==Btn_select_rooms)
{
if(Tv_noofnights.getText().toString()=="0" || Tv_noofnights.getText().toString().equalsIgnoreCase("0"))
{
Toast.makeText(itemsDetailActivity.this, "Please select number of nights",Toast.LENGTH_LONG).show();
}
else if((Tv_spinner1.getText().toString()=="Adults" || Tv_spinner1.getText().toString().equalsIgnoreCase("Adults")) && (Tv_spinner2.getText().toString()=="Infants" || Tv_spinner2.getText().toString().equalsIgnoreCase("Infants")) && (Tv_spinner3.getText().toString()=="Child" || Tv_spinner3.getText().toString().equalsIgnoreCase("Child")))
{
Toast.makeText(itemsDetailActivity.this, "Please select guests",Toast.LENGTH_LONG).show();
}

else
{
String adult,infant,child;
if(spin1==true)
adult=Tv_spinner1.getText().toString();
else
adult="No";
if(spin2==true)
infant=Tv_spinner2.getText().toString();
else
infant="No";
if(spin3==true)
child=Tv_spinner3.getText().toString();
else
child="No";

i=new Intent(this,SelectRoomsActivity.class);
i.putExtra("itemName", itemArrayList.get(0).getitemName());
i.putExtra("checkindate", Tv_comletedate.getText().toString());
i.putExtra("checkoutdate", Tv_complete_date_checkout.getText().toString()+" "+Tv_comletedate_checkout.getText().toString());
i.putExtra("itemid", itemID);
i.putExtra("noOfnights", Tv_value.getText().toString());
i.putExtra("adult", adult);
i.putExtra("infant", infant);
i.putExtra("child", child);
i.putExtra("class", "item");
settings = getSharedPreferences("My_Pref", 0);
editor=settings.edit();
editor.putString("address", Tv_itemlocation.getText().toString());
editor.putString("infant", infant);
editor.putString("child", child);
editor.putString("adult", adult);

editor.commit();


startActivity(i);

//itemsDetailActivity.this.finish();
}
}
else if(v== Tv_checkindate||v==Tv_month||v==Tv_date||v==Tv_comletedate)
{
showDialog(DATE_PICKER_ID);
}
else if(v== Tv_checkoutdate||v==Tv_month_checkout||v==Tv_date_checkout||v==Tv_comletedate_checkout)
{
showDialog(DATE_PICKER_ID_OUT);
}

else if(v==Tv_spinner1||v==Imgv_spinner1)
{
AlertDialog.Builder builder = new AlertDialog.Builder(itemsDetailActivity.this);
builder.setTitle("Adults");
builder.setItems(numbers, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
if(item==0){
Tv_spinner1.setText("Adults");
}else{
Tv_spinner1.setText(numbers[item]);
spin1=true;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}

else if(v==txtheaderclose)
{
if((itemArrayList.get(0).getitemLatitude().equals("") || itemArrayList.get(0).getitemLatitude()=="")||(itemArrayList.get(0).getitemLongitude().equalsIgnoreCase("") || itemArrayList.get(0).getitemLongitude()==""))
{
Intent map2=new Intent(itemsDetailActivity.this,MapActivity.class);
map2.putExtra("latitude","17.385044");
map2.putExtra("longitude", "78.486671");
map2.putExtra("itemname", itemArrayList.get(0).getitemName());
startActivity(map2);
Toast.makeText(itemsDetailActivity.this, "Lat Long not available, so displays only trial map.", Toast.LENGTH_LONG).show();
}
else
{
Intent map2=new Intent(itemsDetailActivity.this,MapActivity.class);
map2.putExtra("latitude", itemArrayList.get(0).getitemLatitude());
map2.putExtra("longitude", itemArrayList.get(0).getitemLongitude());
map2.putExtra("itemname", itemArrayList.get(0).getitemName());
startActivity(map2);
}
}

else if(v==Tv_spinner2||v==Imgv_spinner2)
{
AlertDialog.Builder builder = new AlertDialog.Builder(itemsDetailActivity.this);
builder.setTitle("Infants");
builder.setItems(numbers, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(item==0){
Tv_spinner2.setText("Infants");
}else{
Tv_spinner2.setText(numbers[item]);
spin2=true;
}
}
});
AlertDialog alert = builder.create();
alert.show();


}
else if(v==Tv_spinner3||v==Imgv_spinner3)
{
AlertDialog.Builder builder = new AlertDialog.Builder(itemsDetailActivity.this);
builder.setTitle("Child");
builder.setItems(numbers, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(item==0){
Tv_spinner3.setText("Child");
}else{
Tv_spinner3.setText(numbers[item]);
spin3=true;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}

else if(v==Imgv_plussign){
Log.d("src", "Increasing value...");
counter++;
stringVal = Integer.toString(counter);
Tv_value.setText(stringVal);
Tv_noofnights.setText(stringVal);
day= c.get(Calendar.DAY_OF_MONTH);

day++;
c.set(Calendar.DATE, day);
year  = c.get(Calendar.YEAR);
day= c.get(Calendar.DAY_OF_MONTH);
int lastDay = Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
Log.d("System out", ""+lastDay);
String monthname = null ;
if(day>lastDay)
{
c.add(Calendar.MONTH, 1);
c.set(Calendar.DATE, 1);
c.set(Calendar.YEAR, year+1);
day= c.get(Calendar.DAY_OF_MONTH);
year  = c.get(Calendar.YEAR);
}

month = c.get(Calendar.MONTH);
// Show current date

SimpleDateFormat format1 = new SimpleDateFormat("MM");
SimpleDateFormat format2 = new SimpleDateFormat("MMMM");

try
{
monthname = format2.format(format1.parse(""+(month + 1)));
}
catch (ParseException e)
{
e.printStackTrace();
}
System.out.println(monthname);

stringdate= Integer.toString(day);

Tv_date_checkout.setText(stringdate);
Tv_complete_date_checkout.setText(stringdate);
Tv_month_checkout.setText(monthname);
Tv_comletedate_checkout.setText(monthname+" "+year);
// Tv_comletedate.setText(new StringBuilder()
// .append(monthname)
// .append(" ").append(year)
// .append(" "));
}

else if(v==Imgv_minussign){

Log.d("src", "Decreasing value...");
if(counter>0){

counter--;
stringVal = Integer.toString(counter);
Tv_value.setText(stringVal);
Tv_noofnights.setText(stringVal);

day--;
c.set(Calendar.DATE, day);
day= c.get(Calendar.DAY_OF_MONTH);
int lastDay = Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
Log.d("System out", ""+lastDay);
String monthname = null ;
if(day>lastDay){
c.add(Calendar.MONTH, -1);
c.set(Calendar.DATE, -1);
day= c.get(Calendar.DAY_OF_MONTH);
year  = c.get(Calendar.YEAR);

}

month = c.get(Calendar.MONTH);
// Show current date

SimpleDateFormat format1 = new SimpleDateFormat("MM");
SimpleDateFormat format2 = new SimpleDateFormat("MMMM");

try
{
monthname = format2.format(format1.parse(""+(month + 1)));
}
catch (ParseException e)
{
e.printStackTrace();
}
System.out.println(monthname);

stringdate= Integer.toString(day);
Tv_date_checkout.setText(stringdate);
Tv_complete_date_checkout.setText(stringdate);
Tv_month_checkout.setText(monthname);
Tv_comletedate_checkout.setText(monthname+" "+year);




// stringdate= Integer.toString(day);
// Tv_date_checkout.setText(stringdate);
// Tv_complete_date_checkout.setText(stringdate);
}
}
else if(v==Tv_item_description)
{
Intent desc=new Intent(itemsDetailActivity.this,AboutUsActivity.class);
desc.putExtra("itemId", itemID);
desc.putExtra("itemName",itemArrayList.get(0).getitemName());
Log.i("System out","item Name --->: "+itemName);
startActivity(desc);

}

}

private String getCompleteAddressString(double longitude, double latitude) {
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(longitude, latitude, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");

for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
Log.w("My Current loction address", "----------------" + strAdd);
} else {
Log.w("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current loction address", "Canont get Address!");
}
return strAdd;
}
/*@Override
public void onItemClick(QuickAction source, int pos, int actionId)
{

Toast.makeText(itemsDetailActivity.this, "values"+actionId+" "+pos+" ", Toast.LENGTH_LONG).show();
}*/

private Bitmap LoadImage(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try {
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (NullPointerException e) {
// TODO: handle exception
e.printStackTrace();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}

private InputStream OpenHttpConnection(String strURL) throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();

try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();

if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
public void postOnWall(String msg)
{
String access_token = preferences.getString("access_token", null);
long expires = preferences.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}

if (facebook.isSessionValid()) {

try {
Bundle parameters = new Bundle();
String link = msg;
parameters.putString("picture", link);
parameters.putString("name", getString(R.string.app_name)+" "+itemname);
parameters.putString("description", shareArray.get(1).getSettings_value().replace("{itemName}", itemname));
parameters.putString("caption", " ");
facebook.dialog(itemsDetailActivity.this, "stream.publish",
parameters, new DialogListener() {
// @Override
public void onComplete(Bundle values) {

Toast.makeText(itemsDetailActivity.this,
"Facebook sharing done.",
Toast.LENGTH_LONG).show();
setResult(RESULT_OK);
}

// @Override
public void onFacebookError(FacebookError error) {
}

// @Override
public void onError(DialogError e) {
}

// @Override
public void onCancel() {
itemsDetailActivity.this.finish();
}
});// "stream.publish" is an API call
} catch (Exception e) {
// TODO: handle exception
}
} else {
new FbLoginCommon(itemsDetailActivity.this, msg);
}

}


@Override
protected Dialog onCreateDialog(int id) {

if (id==DATE_PICKER_ID)
{
Log.d("Hello", "====>yes in call dialog");

// Calendar c1 = Calendar.getInstance();
// year  = c1.get(Calendar.YEAR);
// month = c1.get(Calendar.MONTH);
// day   = c1.get(Calendar.DAY_OF_MONTH);
// m=month;
// d=day;
// y=year;
//
// dp=new DatePickerDialog(this, pickerListener, year, month, day);
//    return dp;

switch (id)
{
        case DATE_PICKER_ID:

        year  = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day   = c.get(Calendar.DAY_OF_MONTH);
// m=month;
// d=day;
// y=year;
       
        dp=new DatePickerDialog(this,
                        pickerListener,
                        year, month, day);
        return dp;
     
        }
     

}
if (id != DIALOG_GET_GOOGLE_PLAY_SERVICES) {
return super.onCreateDialog(id);
}

int available = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (available == ConnectionResult.SUCCESS) {
return null;
}
if (GooglePlayServicesUtil.isUserRecoverableError(available)) {
return GooglePlayServicesUtil.getErrorDialog(available, this,
REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES, this);
}
return new AlertDialog.Builder(this)
.setMessage(R.string.plus_generic_error).setCancelable(true)
.setOnCancelListener(this).create();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_SHARING, mSharing);
}

@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
case REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES:
handleResult(resultCode);
break;

case REQUEST_CODE_INTERACTIVE_POST:
mSharing = false;
if (resultCode != RESULT_OK) {
Log.e(TAG, "Failed to create interactive post");
}
break;
}
}

private void handleResult(int resultCode)
{
if (resultCode == RESULT_OK) {
// onActivityResult is called after onStart (but onStart is not
// guaranteed to be called while signing in), so we should make
// sure we're not already connecting before we call connect again.
if (!mPlusClient.isConnecting() && !mPlusClient.isConnected()) {
mPlusClient.connect();
}
} else {
Log.e(TAG, "Unable to sign the user in.");
finish();
}
}

private Intent getInteractivePostIntent() {

try {
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
bm = LoadImage(getString(R.string.url_image_items)+jsonParserData.getitemImage(), bmOptions);
extStorageDirectory = Environment.getExternalStorageDirectory()
.toString() + "/image_folder";

OutputStream outStream = null;

File wallpaperDirectory = new File(extStorageDirectory);
wallpaperDirectory.mkdirs();
outputFile = new File(wallpaperDirectory, "image.PNG");

outStream = new FileOutputStream(outputFile);

bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();

} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

String action = "/?view=true";
Uri callToActionUrl = Uri
.parse(getString(R.string.plus_example_deep_link_url) + action);
String callToActionDeepLinkId = getString(R.string.plus_example_deep_link_id)
+ action;
Log.d("hello", "----->iteractivepost"+getString(R.string.url_image_items)+getitemImage);
PlusShare.Builder builder = new PlusShare.Builder(itemsDetailActivity.this);

builder.setText(""+shareArray.get(2).getSettings_value().replace("{itemName}", itemname));
builder.setType("text/plain");
builder.setContentDeepLinkId("jpg/png", /** Deep-link identifier */
getString(R.string.app_name), /** Snippet title */
" ",
Uri.parse(getString(R.string.url_image_items)+getitemImage));

return builder.getIntent();
}

@Override
public void onConnected(Bundle connectionHint)
{
if (!mSharing) {
// The share button hasn't been clicked yet.
return;
}
String accountName = mPlusClient.getAccountName();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG)
.show();
mSharing = false;
startActivityForResult(getInteractivePostIntent(),
REQUEST_CODE_INTERACTIVE_POST);
}

@Override
public void onDisconnected() {
// Do nothing.
}

@Override
public void onConnectionFailed(ConnectionResult result) {
if (!mSharing) {
return;
}

try {
result.startResolutionForResult(this, REQUEST_CODE_SIGN_IN);
} catch (IntentSender.SendIntentException e) {
// Try to connect again and get another intent to start.
mPlusClient.connect();
}
}

@Override
public void onCancel(DialogInterface dialogInterface) {
Log.e(TAG, "Unable to sign the user in.");
finish();
}


// private Intent generateCustomChooserIntent(Intent prototype,
//            String[] forbiddenChoices)
//    {
//        List<Intent> targetedShareIntents = new ArrayList<Intent>();
//        List<HashMap<String, String>> intentMetaInfo = new ArrayList<HashMap<String, String>>();
//        Intent chooserIntent;
//
//        Intent dummy = new Intent(prototype.getAction());
//        dummy.setType(prototype.getType());
//        List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(dummy,0);
//
//        if (!resInfo.isEmpty())
//        {
//            for (ResolveInfo resolveInfo : resInfo)
//            {
//                if (resolveInfo.activityInfo == null
//                        || Arrays.asList(forbiddenChoices).contains(
//                                resolveInfo.activityInfo.packageName))
//                    continue;
//                //Get all the posible sharers
//                HashMap<String, String> info = new HashMap<String, String>();
//                info.put("packageName", resolveInfo.activityInfo.packageName);
//                info.put("className", resolveInfo.activityInfo.name);
//                String appName = String.valueOf(resolveInfo.activityInfo
//                        .loadLabel(getPackageManager()));
//                info.put("simpleName", appName);
//                //Add only what we want
//                if (Arrays.asList(nameOfAppsToShareWith).contains(
//                        appName.toLowerCase()))
//                {
//                    intentMetaInfo.add(info);
//                }
//            }
//
//            if (!intentMetaInfo.isEmpty())
//            {
//                // sorting for nice readability
//                Collections.sort(intentMetaInfo,
//                        new Comparator<HashMap<String, String>>()
//                        {
//                            @Override public int compare(
//                                    HashMap<String, String> map,
//                                    HashMap<String, String> map2)
//                            {
//                                return map.get("simpleName").compareTo(
//                                        map2.get("simpleName"));
//                            }
//                        });
//
//                // create the custom intent list
//                for (HashMap<String, String> metaInfo : intentMetaInfo)
//                {
//                    Intent targetedShareIntent = (Intent) prototype.clone();
//                    targetedShareIntent.setPackage(metaInfo.get("packageName"));
//                    targetedShareIntent.setClassName(
//                            metaInfo.get("packageName"),
//                            metaInfo.get("className"));
//                    targetedShareIntents.add(targetedShareIntent);
//                }
//                //String shareVia = getString(R.string.offer_share_via);
//                String shareVia = "hello share this";
//                String shareTitle = shareVia.substring(0, 1).toUpperCase()
//                        + shareVia.substring(1);
//                chooserIntent = Intent.createChooser(targetedShareIntents
//                        .remove(targetedShareIntents.size() - 1), shareTitle);
//                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
//                        targetedShareIntents.toArray(new Parcelable[] {}));
//                return chooserIntent;
//            }
//        }
//
//        return Intent.createChooser(prototype,"hello share this"
//                /*getString(R.string.offer_share_via)*/);
//    }

@SuppressWarnings("deprecation")
@SuppressLint("SimpleDateFormat")
public Date formatedate(String date1)
{
String[] d=date1.split(" ");
Log.d("date", "formatted date"+d[0]+" "+d[1]+" "+d[2]+" "+d[3]);

SimpleDateFormat originalFormatcin = new SimpleDateFormat("yyyy-MM-dd");
   SimpleDateFormat targetFormatcin = new SimpleDateFormat("EEE dd MMM yyyy");

    Date datecin,dt=null;
  String cindate="";
  try
  {
  datecin = targetFormatcin.parse(date1);
      cindate=originalFormatcin.format(datecin);
      dt=originalFormatcin.parse(cindate);
      return dt;
   }
  catch (ParseException ex) {}

  return dt;
}


}


***********************************************************************************************************************

FileCache.java

Note: To image handle in JSON

package com.rakesht;

import java.io.File;

import android.content.Context;

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(),"CF");
        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();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
    }

}


***************************************************************************************

ImageLoader.java

package com.rakesht;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class ImageLoader {

MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private final Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
Thread th;
Context context;
AnimationListener listener;
SharedPreferences preferences;

public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
this.context = context;
preferences = context.getSharedPreferences("My_Pref", 0);
this.context = context;
listener = new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}

@Override
public void onAnimationRepeat(Animation animation) {
}

@Override
public void onAnimationEnd(Animation animation) {
// System.out.println("End Animation!");
// load_animations();
}
};
}

final int stub_id = R.drawable.noimage1;
final int stub_id1 = R.drawable.noimage1;

public void DisplayImage(String url, ImageView imageView) {

Log.i("System out", "in DisplayImage :" + url);

imageViews.put(imageView, url);

Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
// Log.i("System out", "in DisplayImage:local");
imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));
} else {
// Log.i("System out", "in DisplayImage:web");
imageView.setBackgroundDrawable(context.getResources().getDrawable(
stub_id));
// new AnimationUtils();
// Animation rotation = AnimationUtils.loadAnimation(context,
// R.anim.rotation);
// rotation.setAnimationListener(listener);
// imageView.startAnimation(rotation);
queuePhoto(url, imageView);

}
}

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

private 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;
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;
} 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++; }
*
* // decode with inSampleSize BitmapFactory.Options o2 = new
* BitmapFactory.Options(); o2.inSampleSize = scale;
*/
return BitmapFactory.decodeStream(new FileInputStream(f));
} 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;
}

@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() {
Log.d("System out", "111111111");
photoToLoad.imageView.clearAnimation();
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setBackgroundDrawable(new BitmapDrawable(
bitmap));
else {
Log.d("System out", "22222222222");
if (preferences.getBoolean("img_contact", false)) {
photoToLoad.imageView.setBackgroundDrawable(context
.getResources().getDrawable(stub_id));
} else {
photoToLoad.imageView.setBackgroundDrawable(context
.getResources().getDrawable(stub_id1));
}
}

}
}

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

}


********************************************************************************

MemoryCache.java



package com.rakesht;

import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import android.graphics.Bitmap;

public class MemoryCache {
    private Map<String, SoftReference<Bitmap>> cache=Collections.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());
    
    public Bitmap get(String id){
        if(!cache.containsKey(id))
            return null;
        SoftReference<Bitmap> ref=cache.get(id);
        return ref.get();
    }
    
    public void put(String id, Bitmap bitmap){
        cache.put(id, new SoftReference<Bitmap>(bitmap));
    }

    public void clear() {
        cache.clear();
    }
}

******************************************************************************************************************************

Utils.java


package com.rakesht;

import java.io.InputStream;
import java.io.OutputStream;

public class Utils  {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}


************************************************************************************************************************

string.xml

//image urel in string file
<string name="url_image_items">http://http://100.101.130.111/rakesh/admin/images/upload/itemss/</string>
      <string name="url_image_item">http://http://100.101.130.111/rakesh/images/item/</string>
      <string name="url_image_offer">http://http://100.101.130.111/rakesh/images/offer/</string>
      <string name="url_image_gallery">http://http://100.101.130.111/rakesh/images/gallery/</string>



No comments:

Post a Comment