Wednesday 29 May 2013

How to integrate with json webservice in android

Example 1)
private WELCOME_MESSAGE mWELCOME_MESSAGE=null;
    private class WELCOME_MESSAGE extends AsyncTask<String, String, String>{
        @Override
        protected String doInBackground(String... params) {
             String strListURL = getResources().getString(R.string.WELCOME_URL);
            return mCommanClass.GetConnectionObject(strListURL);
        }
        @Override
        protected void onPostExecute(String Result) {
            super.onPostExecute(Result);
            if(Result!=null){
                try{
                    JSONObject mJsonObject = new JSONObject(Result);
                    System.out.println("mJsonObject=="+mJsonObject.toString());
                    strStatus = mJsonObject.getString(Constants.WELCOME_MESSAGE.JSON_STATUS);
                    if(strStatus.equalsIgnoreCase(Constants.WELCOME_MESSAGE.JSON_STATUS_TRUE)){                      
                        strWelcomeMessage = mJsonObject.getString(Constants.WELCOME_MESSAGE.JSON_WELCOME_MESSAGE);
                        WelcomeAlertDialog();
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
            else{
            }
        }
    }   

================================
in values
<string name="WELCOME_URL">http://designer24.ch/kundencenter/uni-fr/webinterface/fetchmsg.php</string>
=================================
in commanclass.java
================
/**This method use for GetConnectionObject to Server
     */
    public String GetConnectionObject(String strUrl) {
        InputStream mInputStream = null;
        try {
            //This is the default apacheconnection.
            HttpClient mHttpClient = new DefaultHttpClient();       
            //Pathe of serverside
            HttpGet mHttpGet = new HttpGet(strUrl);
           
            //get the valu from the saerverside as response.
            HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            mInputStream = mHttpEntity.getContent();
       
          }
          catch (Exception e) {
             // TODO Auto-generated catch block
             Log.e(strTAG,"Error in HttpClient,HttpPost,HttpResponse,HttpEntity");
          }
       
         String strLine = null;
         String strResult = null;
        //convert response in to the string.
        try {
              BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,"iso-8859-1"), 8);
              StringBuilder mStringBuilder = new StringBuilder();
                while((strLine = mBufferedReader.readLine()) != null) {
                  mStringBuilder.append(strLine + "\n");
              }
                mInputStream.close();
                strResult = mStringBuilder.toString();           
           }
           catch (Exception e) {
              //System.out.println("Error in BufferedReadering");
              Log.e(strTAG,"Error in BufferedReadering");
            }
          
        return strResult;          
    }
=============================================
2)    <string name ="SEARCHCUST_URL">http://180.211.110.196/php-projects/wastemanagement/www/soap/searchCustomer.php</string>
OR http://www.letsrecycle.co.in/soap/searchCustomer.php
//****************************************************************************************************************************
    private class getServerData extends AsyncTask<String, String, String>
    {      
             private ProcessDialog mProcessDialog=null;
             protected void onPreExecute() {
                     mProcessDialog = new ProcessDialog(Search_Cust_list.this,Constant.SERVER,Constant.LOADING);
           
                     allData_namevaluepair = new ArrayList<NameValuePair>();
                     allData_namevaluepair.add(new BasicNameValuePair(Constant.SEARCH_CUST_LIST_REQUEST.CODE, edtSearchCustCode.getText().toString()));
                     allData_namevaluepair.add(new BasicNameValuePair(Constant.SEARCH_CUST_LIST_REQUEST.MOBILE,  edtSearchMob.getText().toString()));
                     allData_namevaluepair.add(new BasicNameValuePair(Constant.SEARCH_CUST_LIST_REQUEST.HDNACTION, Constant.SEARCH_CUST_LIST_REQUEST.SEARCH));                             
                    super.onPreExecute();
             }
 
             protected String doInBackground(String... params) {             
                     String search_URL = getResources().getString(R.string.SEARCHCUST_URL);
                     return mCommonClass.PostConnection(search_URL, allData_namevaluepair);                            
             }                   
             protected void onPostExecute(String result) {
                  mProcessDialog.dismiss();
               
                    if(result!=null){ 
                         clearPriviousData();
                         System.out.println("Search_Suct_List Response===="+result);
                         try {
                            JSONObject jsonCustDetails = new JSONObject(result);
                            if(jsonCustDetails.getString(Constant.COMMON_JSON.TYPE).equals(Constant.COMMON_JSON.OK)){
                                    JSONObject jsonCustomers = jsonCustDetails.getJSONObject(Constant.SEARCH_CUST_LIST_REQUEST.CUSTOMERS);
                                    JSONArray jsonArray =  jsonCustomers.names();
                                    for (int j = 0; j < jsonArray.length(); j++) {
                                        JSONObject mJsonObject = jsonCustomers.getJSONObject(jsonArray.getString(j));
                                        custId.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.CUSTOMER_ID));
                                         custSalutation.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.SALUTATION));
                                         custFirst.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.FIRST_NAME));
                                         custMiddleName.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.MIDDLE_NAME));
                                         custLastName.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.LAST_NAME));
                                         custCode.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.CODE));
                                         custEmail.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.EMAIL));
                                         custAdd1.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.ADDRESS1));
                                         custAdd2.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.ADDRESS2));
                                         custCity.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.CITY));
                                         custState.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.STATE));
                                         custCountry.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.COUNTRY));
                                         custZipCode.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.ZIPCODE));
                                         custResiNum.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.R_PHONE));
                                         custOffi.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.O_PHONE));
                                         custMobile.add(mJsonObject.getString(Constant.SEARCH_CUST_LIST_JSON.MOBILE_NO));
                                         SearchCustListAdapter custAdapter = new SearchCustListAdapter(Search_Cust_list.this, custId, custFirst, custCode);
                                         lstCustmorDetails.setAdapter(custAdapter);
                                    }
                            }else{
                                Toast.makeText(Search_Cust_list.this, jsonCustDetails.getString(Constant.COMMON_JSON.ERR_MSG).toString(), Toast.LENGTH_SHORT).show();
                                lstCustmorDetails.setAdapter(null);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        lstCustmorDetails.setOnItemClickListener(new OnItemClickListener() {
                             public void onItemClick(AdapterView<?> arg0,View arg1, int position, long arg3) {
                                 Intent in = new Intent(Search_Cust_list.this,View_Generate_Lead_Activity.class);
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.CUST_ID, custId.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.SALUTATION,custSalutation.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.FIRSTNAME, custFirst.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.MIDDLENAME, custMiddleName.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.LASTNAME, custLastName.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.CODE, custCode.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.EMAIL, custEmail.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.ADD1, custAdd1.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.ADD2, custAdd2.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.CITY, custCity.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.STATE, custState.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.COUNTRY, custCountry.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.ZIPCODE, custZipCode.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.PHONE, custResiNum.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.OFFICE, custOffi.get(position));
                                     in.putExtra(Constant.SEARCH_CUST_LIST_INTENT.MOBILE, custMobile.get(position));
                                 startActivity(in);
                                 finish();
                             }
                         });                      
                    }
                    else{
                        Toast.makeText(Search_Cust_list.this, Constant.SERVERCONNERROR,Toast.LENGTH_SHORT).show();
                    }
                     super.onPostExecute(result);
             }          
        }
******************************************
/**This method use for PostConnection to Server
     */
    public String PostConnection(String strUrl,ArrayList<NameValuePair> alstNameValuePair) {
        InputStream mInputStream = null;
        try {
            //This is the default apacheconnection.
            HttpClient mHttpClient = new DefaultHttpClient();
//            HttpConnectionParams.setConnectionTimeout(mHttpClient.getParams(), 60000); //Timeout Limit
            //Pathe of serverside
            HttpPost mHttpPost = new HttpPost(strUrl);
           
            if(alstNameValuePair!=null)
            {
                //post the valur you want to pass.
                 mHttpPost.setEntity(new UrlEncodedFormEntity(alstNameValuePair));
            }
           
            //get the valu from the saerverside as response.
            HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            mInputStream = mHttpEntity.getContent();
       
          }
          catch (Exception e) {
              e.printStackTrace();
          }
       
         String strLine = null;
         String strResult = "";
       
        //convert response in to the string.
        try {
                if(mInputStream!=null){
                  BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,HTTP.UTF_8), 8);
                  StringBuilder mStringBuilder = new StringBuilder();
                    while((strLine = mBufferedReader.readLine()) != null) {
                      mStringBuilder.append(strLine + "\n");
                  }
                        strResult = mStringBuilder.toString();
                        mInputStream.close();
                }
           }
           catch (Exception e) {
                   e.printStackTrace();
            }
       
         return strResult;
    }
    ================================================
3)
 private SendLocation mSendLocation = null;
      private class SendLocation extends AsyncTask<Location, String, String>
        {   
            protected String doInBackground(Location... location) {
                Log.d(Constant.TAG, "Location Request = " + "doInBackground");
                String strURL=MainActivity.this.getResources().getString(R.string.location_update_url);
                ArrayList<NameValuePair> alstNameValuePair = new ArrayList<NameValuePair>();
                alstNameValuePair.add(new BasicNameValuePair(MainActivity.this.getResources().getString(R.string.Action),MainActivity.this.getResources().getString(R.string.Set)));
                alstNameValuePair.add(new BasicNameValuePair(Constant.LOCATION_UPDATE_REQUEST.DEVICEID,getDeviceID().toString()));
                alstNameValuePair.add(new BasicNameValuePair(Constant.LOCATION_UPDATE_REQUEST.LATITUDE,String.valueOf(location[0].getLatitude()).toString()));
                alstNameValuePair.add(new BasicNameValuePair(Constant.LOCATION_UPDATE_REQUEST.LONGITUDE,String.valueOf(location[0].getLongitude()).toString()));
                alstNameValuePair.add(new BasicNameValuePair(Constant.LOCATION_UPDATE_REQUEST.NO_OF_PEOPLE,String.valueOf(mSharedPreferences_Read.getInt(Constant.SHAREDPREFERENCE.NO_OF_PEOPLE, 1))));
                alstNameValuePair.add(new BasicNameValuePair(Constant.LOCATION_UPDATE_REQUEST.TIMESTAMP, new SimpleDateFormat(Constant.TIME_STAMP_FORMAT).format(new Date(location[0].getTime()))));
                Log.d(Constant.TAG, "Location Request = " + alstNameValuePair.toString());
                return mCommonClass.PostConnection(strURL, alstNameValuePair);
            }                  
           
            protected void onPostExecute(String result) {
                if(result!=null){
                    Log.d(Constant.TAG, "Location Response = " + result.toString());
                }
                else{
                }
                super.onPostExecute(result);
                mSendLocation = null;
            }
        }
************************************************
/**This method use for PostConnection to Server
     */
    public String PostConnection(String strUrl,ArrayList<NameValuePair> alstNameValuePair) {
        InputStream mInputStream = null;
        try {
                //This is the default apacheconnection.
                HttpClient mHttpClient = new DefaultHttpClient();
    //            HttpConnectionParams.setConnectionTimeout(mHttpClient.getParams(), 60000); //Timeout Limit
                //Pathe of serverside
                HttpPost mHttpPost = new HttpPost(strUrl);
               
                if(alstNameValuePair!=null)
                {
                    //post the valur you want to pass.
                     mHttpPost.setEntity(new UrlEncodedFormEntity(alstNameValuePair));
                }
               
                //get the valu from the saerverside as response.
                HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
                HttpEntity mHttpEntity = mHttpResponse.getEntity();
                mInputStream = mHttpEntity.getContent();
       
          }
          catch (Exception e) {
              e.printStackTrace();
          }
       
         String strLine = null;
         String strResult = "";
       
        //convert response in to the string.
        try {
                if(mInputStream!=null){
                  BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,HTTP.UTF_8), 8);
                  StringBuilder mStringBuilder = new StringBuilder();
                    while((strLine = mBufferedReader.readLine()) != null) {
                      mStringBuilder.append(strLine + "\n");
                  }
                        strResult = mStringBuilder.toString();
                        mInputStream.close();
                }
           }
           catch (Exception e) {
                   e.printStackTrace();
            }
       
         return strResult;
     }
================================================
4)/**This class for Accept notification*/
    private class Notification_Accept extends AsyncTask<String, String, String>{
       
        @Override
        protected String doInBackground(String... params) {
                String strURL=getResources().getString(R.string.ACCEPTLEADNOTIFICATION_URL);                       
                ArrayList<NameValuePair> alstNameValuePair = new ArrayList<NameValuePair>();
                alstNameValuePair.add(new BasicNameValuePair(Constant.C2DM_NOTIFICATION_ACCEPT_REQUEST.ADMINUSERID,mSharedPreferencesRead.getString(Constant.LOGIN_SHARED.LS_USERID,"").toString().trim()));
                alstNameValuePair.add(new BasicNameValuePair(Constant.C2DM_NOTIFICATION_ACCEPT_REQUEST.APPOINTMENT_ID,mSharedPreferencesRead.getString(Constant.C2DM_NOTIFICATION_SHARED.CNS_APPOINTMENT_ID,"").toString().trim()));
                alstNameValuePair.add(new BasicNameValuePair(Constant.C2DM_NOTIFICATION_ACCEPT_REQUEST.HDNACTION,Constant.C2DM_NOTIFICATION_ACCEPT_REQUEST.HDNACTION_APPOINTMENT_ACCEPTED));
                return mCommonClass.PostConnection(strURL, alstNameValuePair);
        }
       
        @Override
        protected void onPostExecute(String result) {
                if(result!=null)
              {
                          Log.i(Constant.TAG,"Notification Accept Response = " + result.toString());
                         try {
                                JSONObject jsonnotification = new JSONObject(result);
                             if(jsonnotification.getString(Constant.COMMON_JSON.TYPE).equals(Constant.COMMON_JSON.OK)){
                                    mDialog.dismiss();
                                    finish();
                            }else{
                                Toast.makeText(GetNotification.this, jsonnotification.getString(Constant.COMMON_JSON.ERR_MSG).toString(), Toast.LENGTH_SHORT).show();
                            }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
              }       
                else{
                    Toast.makeText(GetNotification.this, Constant.SERVERCONNERROR,Toast.LENGTH_SHORT).show();
                    Log.e(Constant.TAG, Constant.SERVERCONNERROR);
              }
             super.onPostExecute(result);
        }
    }
**********************************************
/**This method use for PostConnection to Server
     */
    public String PostConnection(String strUrl,ArrayList<NameValuePair> alstNameValuePair) {
        InputStream mInputStream = null;
        try {
            //This is the default apacheconnection.
            HttpClient mHttpClient = new DefaultHttpClient();
//            HttpConnectionParams.setConnectionTimeout(mHttpClient.getParams(), 60000); //Timeout Limit
            //Pathe of serverside
            HttpPost mHttpPost = new HttpPost(strUrl);
           
            if(alstNameValuePair!=null)
            {
                //post the valur you want to pass.
                 mHttpPost.setEntity(new UrlEncodedFormEntity(alstNameValuePair));
            }
           
            //get the valu from the saerverside as response.
            HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            mInputStream = mHttpEntity.getContent();
       
          }
          catch (Exception e) {
              e.printStackTrace();
          }
       
         String strLine = null;
         String strResult = "";
       
        //convert response in to the string.
        try {
                if(mInputStream!=null){
                  BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,HTTP.UTF_8), 8);
                  StringBuilder mStringBuilder = new StringBuilder();
                    while((strLine = mBufferedReader.readLine()) != null) {
                      mStringBuilder.append(strLine + "\n");
                  }
                        strResult = mStringBuilder.toString();
                        mInputStream.close();
                }
           }
           catch (Exception e) {
                   e.printStackTrace();
            }
       
         return strResult;
    }
*********************************
    <string name="ACCEPTLEADNOTIFICATION_URL">http://180.211.110.196/php-projects/wastemanagement/www/soap/acceptLeadNotification.php</string>
OR http://www.letsrecycle.co.in/soap/acceptLeadNotification.php
=============================================
Commanclass.java
package com.ovte.letsrecycle;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class CommonClass {
   
    //this method sends an intent to the c2dm server to register the app with the c2dm server
    public static void C2DM_Register(Context context) {
        Log.w(Constant.TAG, "Start C2DM Registration Process");
       
        Intent mIntent = new Intent(Constant.C2DM.ACTION.REGISTER);
       
        mIntent.putExtra(Constant.C2DM.APP, PendingIntent.getBroadcast(context, 0, new Intent(), 0));
       
        // Sender currently not used[This changes for different users]
        mIntent.putExtra(Constant.C2DM.SENDER,Constant.C2DM.SENDER_EMAILID);
   
        context.startService(mIntent);
    }
   
    private ConnectivityManager connectivity=null;
    private NetworkInfo netinfo=null;
    /**This method use for check Network Connectivity
     */
    public boolean CheckNetwork(Context mContext) {
            this.connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            this.netinfo= connectivity.getActiveNetworkInfo();
            if(netinfo!=null && netinfo.isConnected()==true)
            {         
                return true;
            }
            else
            {
                Toast.makeText(mContext, Constant.NETWORK_NOT_AVAILABLE, Toast.LENGTH_LONG).show();
                return false;          
            }
       
    }
   
    /**This method use for check Network Connectivity No Message
     */
    public boolean CheckNetworkNoMessage(Context mContext) {
            this.connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            this.netinfo= connectivity.getActiveNetworkInfo();
            if(netinfo!=null && netinfo.isConnected()==true)
            {
                return true;
            }
            else
            {
                return false;          
            }
       
    }
   
    /**This function use for check service running or not*/
    public static boolean IsServiceRunning(Context context,String package_class) {
        ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (package_class.equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
   
   
    /**This method use for PostConnection to Server
     */
    public String PostConnection(String strUrl,ArrayList<NameValuePair> alstNameValuePair) {
        InputStream mInputStream = null;
        try {
            //This is the default apacheconnection.
            HttpClient mHttpClient = new DefaultHttpClient();
//            HttpConnectionParams.setConnectionTimeout(mHttpClient.getParams(), 60000); //Timeout Limit
            //Pathe of serverside
            HttpPost mHttpPost = new HttpPost(strUrl);
           
            if(alstNameValuePair!=null)
            {
                //post the valur you want to pass.
                 mHttpPost.setEntity(new UrlEncodedFormEntity(alstNameValuePair));
            }
           
            //get the valu from the saerverside as response.
            HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            mInputStream = mHttpEntity.getContent();
       
          }
          catch (Exception e) {
              e.printStackTrace();
          }
       
         String strLine = null;
         String strResult = "";
       
        //convert response in to the string.
        try {
                if(mInputStream!=null){
                  BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,HTTP.UTF_8), 8);
                  StringBuilder mStringBuilder = new StringBuilder();
                    while((strLine = mBufferedReader.readLine()) != null) {
                      mStringBuilder.append(strLine + "\n");
                  }
                        strResult = mStringBuilder.toString();
                        mInputStream.close();
                }
           }
           catch (Exception e) {
                   e.printStackTrace();
            }
       
         return strResult;
    }
   
    /**This method use for GetConnection to Server
     */
    public String GetConnection(String strUrl) {
        InputStream mInputStream = null;
        try {
            //This is the default apacheconnection.
            HttpClient mHttpClient = new DefaultHttpClient();
//            HttpConnectionParams.setConnectionTimeout(mHttpClient.getParams(), 60000); //Timeout Limit
            //Pathe of serverside
            HttpGet mHttpGet = new HttpGet(strUrl);
           
            //get the valu from the saerverside as response.
            HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            mInputStream = mHttpEntity.getContent();
       
          }
          catch (Exception e) {
            e.printStackTrace();
          }
       
         String strLine = null;
         String strResult = null;
        //convert response in to the string.
        try {
              BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,HTTP.UTF_8), 8);
              StringBuilder mStringBuilder = new StringBuilder();
                while((strLine = mBufferedReader.readLine()) != null) {
                  mStringBuilder.append(strLine + "\n");
              }
                mInputStream.close();
                strResult = mStringBuilder.toString();           
           }
           catch (Exception e) {
             e.printStackTrace();
            }
       
         return strResult;
    }
   
    /**This method use for GETHTTPConnection to Server
     */
    public String GETHTTPConnection(String strUrl)
    {
        HttpURLConnection mHttpURLConnection=null;
        int intResponse = -1;
        try{
                URL mURL = new URL(strUrl);
                URLConnection mURLConnection = mURL.openConnection();
                    
                if (!(mURLConnection instanceof HttpURLConnection)) {          
                       Log.e(Constant.TAG,"Error in HTTP connection Not Connect");
                    throw new IOException("Not an HTTP connection");
                }
               
                mHttpURLConnection = (HttpURLConnection) mURLConnection;
                mHttpURLConnection.setRequestMethod("GET");
                mHttpURLConnection.setUseCaches (false);
                mHttpURLConnection.setDoInput(true);
                mHttpURLConnection.setDoOutput(true);
                mHttpURLConnection.setInstanceFollowRedirects(true);
                mHttpURLConnection.connect();
                intResponse = mHttpURLConnection.getResponseCode();
               
                if (intResponse == HttpURLConnection.HTTP_OK) {
                    return InputStreamToString(mHttpURLConnection.getInputStream());                                      
                }
                else{
                    return null;
                }
        }           
        catch (Exception e)
        {
            e.printStackTrace(); 
            return null;
        }
        finally{
            if(mHttpURLConnection!=null){
                mHttpURLConnection.disconnect();
            }
        }
    }
   
    /**This method use for POSTHTTPConnection to Server
     */
    public String POSTHTTPConnection(String strUrl,String[] Key,String[] Value)
    {
        HttpURLConnection mHttpURLConnection=null;
        int intResponse = -1;
        try{
                URL mURL = new URL(strUrl);
                URLConnection mURLConnection = mURL.openConnection();
                    
                if (!(mURLConnection instanceof HttpURLConnection)) {          
                       Log.e(Constant.TAG,"Error in HTTP connection Not Connect");
                    throw new IOException("Not an HTTP connection");
                }
               
                mHttpURLConnection = (HttpURLConnection) mURLConnection;
                mHttpURLConnection.setRequestMethod("POST");
                mHttpURLConnection.setUseCaches (false);
                mHttpURLConnection.setDoInput(true);
                mHttpURLConnection.setDoOutput(true);
                mHttpURLConnection.setInstanceFollowRedirects(true);
                /**This comment code use if encode request UTF_8 format*/
                /*                String Query = String.format("version=%s", URLEncoder.encode("android", HTTP.UTF_8));
                                mHttpURLConnection.setRequestProperty("Accept-Charset", HTTP.UTF_8);
                                mHttpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" +  HTTP.UTF_8);
                                output.write(Query.getBytes(HTTP.UTF_8));*/
               
//                /**This code use for post request*/
                StringBuffer Query = new StringBuffer();
                if(Key!=null || Value!=null){
                    for(int i=0;i < Key.length;i++){
                        Query.append(String.format("%s=%s",Key[i],Value[i]).toString().trim());
                        if(i >= 0 && i < (Key.length -1) && Key.length > 1){
                            Query.append("&");
                        }
                    }
                }
              
                OutputStream mOutputStream = null;
                try {
                     mOutputStream = mHttpURLConnection.getOutputStream();
                     Log.i("Request = ", Query.toString());
                     mOutputStream.write(Query.toString().getBytes());
                } finally {
                     if (mOutputStream != null) try { mOutputStream.close(); } catch (IOException logOrIgnore) {}
                }

                mHttpURLConnection.connect();
                intResponse = mHttpURLConnection.getResponseCode();
               
                if (intResponse == HttpURLConnection.HTTP_OK) {
                    return InputStreamToString(mHttpURLConnection.getInputStream());                                
                }
                else{
                    return null;
                }
        }           
        catch (Exception e)
        {
            e.printStackTrace(); 
            return null;
        }
        finally{
            if(mHttpURLConnection!=null){
                mHttpURLConnection.disconnect();
            }
        }
    }
   
    /**This method use for convert InputStream To String
     */
    private String InputStreamToString(InputStream mInputStream){
         String strLine = null;
        //convert response in to the string.
        try {
              if(mInputStream!=null){
                  BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,HTTP.UTF_8), 8);
                  StringBuilder mStringBuilder = new StringBuilder();
                    while((strLine = mBufferedReader.readLine()) != null) {
                      mStringBuilder.append(strLine);
                  }
                    mInputStream.close();
                    return mStringBuilder.toString();       
              }
              else{
                  return null;
              }
           }
           catch (Exception e) {
               e.printStackTrace();
               return null;
          }
          
//        try{
//                byte[] bytes = new byte[1024];
//                StringBuilder mStringBuilder = new StringBuilder();
//                int count = 0;
//                while ((count = mInputStream.read(bytes))  != -1) {
//                    mStringBuilder.append(new String(bytes, 0, count));
//                }
//                  mInputStream.close();
//                  return mStringBuilder.toString();   
//         }
//         catch (Exception e) {
//            e.printStackTrace();
//            return null;
//         }
    }
   
    /**This method use for PostConnectionInputStream to Server
     */
    public InputStream PostConnectionInputStream(String strUrl,ArrayList<NameValuePair> alstNameValuePair) {
        try {
                //This is the default apacheconnection.
                HttpClient mHttpClient = new DefaultHttpClient();
//                HttpConnectionParams.setConnectionTimeout(mHttpClient.getParams(), 60000); //Timeout Limit
                //Pathe of serverside
                HttpPost mHttpPost = new HttpPost(strUrl);
               
                if(alstNameValuePair!=null)
                {
                    //post the valur you want to pass.
                     mHttpPost.setEntity(new UrlEncodedFormEntity(alstNameValuePair));
                }
               
                //get the valu from the saerverside as response.
                HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
                HttpEntity mHttpEntity = mHttpResponse.getEntity();
                return mHttpEntity.getContent();
          }
          catch (Exception e) {
                e.printStackTrace();
                 return null;
          }       
    }
   
     /**This method use to Check Memory Card
     */ 
    public Boolean MemoryCardCheck() {
       
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
   
     /**This method use to Write File String
     */ 
    public void WriteString(String FilePath,String Text){
        try{
                File mFile=new File(FilePath);
                FileOutputStream mFileOutputStream = new FileOutputStream(mFile);
                OutputStreamWriter mOutputStreamWriter = new OutputStreamWriter(mFileOutputStream);
                mOutputStreamWriter.write(Text);
                mOutputStreamWriter.flush();
                mOutputStreamWriter.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
   
     /**This method use for take backup of application
     */
    public static void DatabaseBackup(String currentDBPath,String backupDBPath,String Messagetext,Context context){
            try {
                   File sd = Environment.getExternalStorageDirectory();
                   File data = Environment.getDataDirectory();

                   if (sd.canWrite()) {
                       File currentDB = new File(data, currentDBPath);
                       File backupDB = new File(sd, backupDBPath);
//                       Toast.makeText(this,"" + currentDB.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                       if (currentDB.exists()) {
                          
                           FileChannel src = new FileInputStream(currentDB).getChannel();
                           FileChannel dst = new FileOutputStream(backupDB).getChannel();
                           dst.transferFrom(src, 0, src.size());
                           src.close();
                           dst.close();
                              Toast.makeText(context,Messagetext, Toast.LENGTH_SHORT).show();
                       }
                   }
               } catch (Exception e) {
                   e.printStackTrace();
            }
       }
}
===============================================
5)    /*************************************  Class used for Getting UserList by DHL  *****************************************/
   
    private class Get_UserList_From_Servier extends
            AsyncTask<String, String, String> {

        private ProcessDialog mProcessDialog = null;

        protected void onPreExecute() {
            mProcessDialog = new ProcessDialog(Report.this, Constant.SERVER,Constant.LOADING);
            mALST_UserName = new ArrayList<String>();
            mALST_UserId = new ArrayList<String>();
            super.onPreExecute();
        }

        protected String doInBackground(String... params) {
            String strURL = getResources().getString(R.string.LOGIN_URL);
            ArrayList<NameValuePair> mNameValuePair = new ArrayList<NameValuePair>();
            mNameValuePair.add(new BasicNameValuePair(Constant.USER_LIST.USER_ID,mSharedPreferences.getString(Constant.LOGIN_SHARED.LS_USERID, "")));
            mNameValuePair.add(new BasicNameValuePair(Constant.LOGIN_REQUEST.HDN_ACTION,Constant.LOGIN_REQUEST.HDN_ACTION_USERLIST));
            return mCommonClass.PostConnection(strURL, mNameValuePair);
        }

        protected void onPostExecute(String result) {
            mProcessDialog.dismiss();
            if (result != null) {
                Log.i(Constant.TAG + " Report ", "Login Response = " + result);
                try {
                    JSONObject jsonLogingDetails = new JSONObject(result);
                    if (jsonLogingDetails.getString(Constant.COMMON_JSON.TYPE).equals(Constant.COMMON_JSON.OK)) {

                        JSONObject jsonAdminUser = jsonLogingDetails.getJSONObject(Constant.USER_LIST.ADMINUSERLIST);
//                        Log.i(Constant.TAG,"Admin :---->  " + jsonAdminUser.toString());
//                        Log.i(Constant.TAG, "Names :--- "    + jsonAdminUser.names().toString());
                        JSONArray jsonArray = jsonAdminUser.names();
                        mALST_UserId.add("100000000");
                        mALST_UserName.add("ALL");
                        for (int j = 0; j < jsonArray.length(); j++) {
                            JSONObject jsonOBJName = jsonAdminUser.getJSONObject(jsonArray.getString(j).toString());
//                            System.out.println("====> "    + jsonOBJName.getString(Constant.LOGIN_JSON.USERID.toString()));
//                            System.out.println("====> "    + jsonOBJName.getString(Constant.LOGIN_JSON.USERNAME.toString()));
                            mALST_UserId.add(jsonOBJName.getString(Constant.LOGIN_JSON.USERID.toString()));
                            mALST_UserName.add(jsonOBJName.getString(Constant.LOGIN_JSON.USERNAME.toString()));
                        }
                    }
                    getuserName();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(Report.this, Constant.SERVERCONNERROR,
                        Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(result);
        }
    }
***************************************************
/**This method use for PostConnection to Server
     */
    public String PostConnection(String strUrl,ArrayList<NameValuePair> alstNameValuePair) {
        InputStream mInputStream = null;
        try {
            //This is the default apacheconnection.
            HttpClient mHttpClient = new DefaultHttpClient();
//            HttpConnectionParams.setConnectionTimeout(mHttpClient.getParams(), 60000); //Timeout Limit
            //Pathe of serverside
            HttpPost mHttpPost = new HttpPost(strUrl);
           
            if(alstNameValuePair!=null)
            {
                //post the valur you want to pass.
                 mHttpPost.setEntity(new UrlEncodedFormEntity(alstNameValuePair));
            }
           
            //get the valu from the saerverside as response.
            HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            mInputStream = mHttpEntity.getContent();
       
          }
          catch (Exception e) {
              e.printStackTrace();
          }
       
         String strLine = null;
         String strResult = "";
       
        //convert response in to the string.
        try {
                if(mInputStream!=null){
                  BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,HTTP.UTF_8), 8);
                  StringBuilder mStringBuilder = new StringBuilder();
                    while((strLine = mBufferedReader.readLine()) != null) {
                      mStringBuilder.append(strLine + "\n");
                  }
                        strResult = mStringBuilder.toString();
                        mInputStream.close();
                }
           }
           catch (Exception e) {
                   e.printStackTrace();
            }
       
         return strResult;
    }

******************************************
http://www.letsrecycle.co.in/soap/adminLogin.php

   

No comments:

Post a Comment