Monday, December 22, 2014

WebAPIRequest.cs

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class WebAPIRequest
{
    public static String convertStreamToString(InputStream is)
            throws IOException {
        if (is != null)
        {
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                is.close();
            }
            return sb.toString();
        } else {
            return "";
        }
    }

    public Document performPost(String url, String body) {
        Document doc = null;

        try {

            HttpParams basicparams = new BasicHttpParams();
            URI uri = new URI(url);
            HttpPost method = new HttpPost(uri);
            int timeoutConnection = 60000;
            HttpConnectionParams.setConnectionTimeout(basicparams,timeoutConnection);
            DefaultHttpClient client = new DefaultHttpClient(basicparams);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            body = body.replaceAll("%20", " ");
            String[] parameters = body.split("&");
            for (int i = 0; i < parameters.length; i++) {
                String[] parameter = parameters[i].split("=");
                if (parameter.length >= 2) {
                    nameValuePairs.add(new BasicNameValuePair(parameter[0],
                            parameter[1]));
                }
            }
            method.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse res = client.execute(method);

            InputStream data = res.getEntity().getContent();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(data);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return doc;
    }

    public String performPostAsString(String url,
            ArrayList<NameValuePair> nameValuePairs) {
        String value = null;

        try {

            HttpParams basicparams = new BasicHttpParams();
            URI uri = new URI(url);
            HttpPost method = new HttpPost(uri);
            int timeoutConnection = 60000;

            HttpConnectionParams.setConnectionTimeout(basicparams,
                    timeoutConnection);
            DefaultHttpClient client = new DefaultHttpClient(basicparams);

            method.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse res = client.execute(method);

            InputStream data = res.getEntity().getContent();
            value = convertStreamToString(data);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return value;
    }

    public String performGet(String url) {

        url = url.replace(" ", "%20");

        System.out.println(url);

        String strres = null;
        try {
            HttpParams basicparams = new BasicHttpParams();
            int timeoutConnection = 60000;
            HttpConnectionParams.setConnectionTimeout(basicparams,
                    timeoutConnection);
            DefaultHttpClient client = new DefaultHttpClient(basicparams);
            URI uri = new URI(url);
            // url.replaceAll("%20"," ");
            HttpGet method = new HttpGet(uri);
            HttpResponse res = client.execute(method);
            InputStream data = res.getEntity().getContent();
            strres = convertStreamToString(data);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return strres;
    }
}


How to use in webservices

 

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

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

import com.Cust.HttpServicepk.WebAPIRequest;

import android.R.string;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
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.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainAtivity extends Activity {
    ListView lv;
   
    String respo = "";
    Button btnback;
   
   
    WebAPIRequest wb = new WebAPIRequest();
    ArrayList<String> CatList = new ArrayList<String>();
    ArrayList<String> CatIDList = new ArrayList<String>();
    DBHelper db = new DBHelper(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnback = (Button) findViewById(R.id.buttonback);
        btnback.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent i = new Intent(getApplicationContext(), Homescr.class);
                startActivity(i);
            }
        });
      
        try
        {
            db.createDataBase();
          
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String url = "http://www.roms.webege.com/service_category.php";

        new display_activity().execute(url);

        lv = (ListView) findViewById(R.id.listView1);

OnItemClickListener clickListener = new OnItemClickListener()
{

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
              
                // String CatID = CatIDList.toArray()[arg2].toString();
                String CatID = CatIDList.get(arg2);
                String Catname = CatList.get(arg2);
                Intent i = new Intent(getApplicationContext(), Item.class);
                i.putExtra("ID", CatID);
                i.putExtra("CatName", Catname);

                startActivity(i);

                Toast.makeText(getApplicationContext(), CatID, 0).show();
            }

        };
        lv.setOnItemClickListener(clickListener);

    }

    public class custlist extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return CatList.toArray().length;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return CatList.toArray()[arg0];
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
            LayoutInflater layoutInflater;
            layoutInflater = getLayoutInflater();
            layoutInflater = LayoutInflater.from(MainAtivity.this);
            arg1 = layoutInflater.inflate(R.layout.raw, null);
            TextView tv = (TextView) arg1.findViewById(R.id.textViewstarter);
            TextView tvid = (TextView) arg1.findViewById(R.id.catid);
            // Log.i("NAME",CatList.toArray()[arg0].toString());
            tv.setText(CatList.toArray()[arg0].toString());
            tvid.setText(CatIDList.toArray()[arg0].toString());
            return arg1;

        }

    }

    public class display_activity extends AsyncTask<String, Void, Void>
    {

        ProgressDialog pd;

        @Override
        protected void onPreExecute()
        {
            // TODO Auto-generated method stub
            super.onPreExecute();
            Log.i("CALL", "CALL");

            pd = ProgressDialog.show(MainAtivity.this, "Loading .....",
                    "Fatching data");

        }

        @Override
        protected Void doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            try {
                respo = wb.performGet(arg0[0]);
                Log.i("JSON", respo);
                Toast.makeText(getApplicationContext(), respo, 0).show();
            } catch (Exception e) {
                // TODO: handle exception

                Log.i("ERROR", e.getMessage().toString());

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Log.i("CALL", "CALL");
          
          
            JSONObject jsonResponse;
            JSONArray jsarray;
          
            // JSONArray CatID;
            try {
                String[] resspdata = respo.toString().trim().split("<!");
                Log.i("SPData", resspdata[0].toString());

                jsonResponse = new JSONObject(respo);
                // Log.i("JSON", jsonResponse.toString());
                jsarray = new JSONArray();
                jsarray = jsonResponse.getJSONArray("members");
                Log.i("JSON", jsarray.getString(1));
                //
              
                //
                for (int i = 0; i < jsarray.length(); i++)
                {
                    JSONObject row = jsarray.getJSONObject(i);
                  
                    String CatName1 = row.getString("CatName");
                    String CatID = row.getString("CatID");
                    CatList.add(CatName1);
                    // Strin = row.getString("name");
                    CatIDList.add(CatID);

                }
                // CatIDList.get(1);
                //

                custlist c = new custlist();
                lv.setAdapter(c);

                // Log.i("AFTJSON", "AFTJSON" + jsonResponse.get("username"));
                // Log.i("AFTJSON", "AFTJSON" + jsonResponse.get("password"));
                // Log.i("AFTJSON", "AFTJSON" + jsonResponse.get("role_id_f"));

            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                // JSONArray js =new JSONArray(respo);

                // Log.i("JSON", js.getString(1));

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                pd.dismiss();
            }

        }

    }
}

Thursday, December 18, 2014


How To Create Session In Android

SessionManager.java

import java.util.HashMap;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SessionManager {
    // Shared Preferences
    SharedPreferences pref;
   
    // Editor for Shared preferences
    Editor editor;
   
    // Context
    Context _context;
   
    // Shared pref mode
    int PRIVATE_MODE = 0;
   
    // Sharedpref file name
    private static final String PREF_NAME = "AndroidHivePref";
   
    // All Shared Preferences Keys
    private static final String IS_LOGIN = "IsLoggedIn";
   
    // User name (make variable public to access from outside)
    public static final String KEY_NAME = "name";
   
    // Email address (make variable public to access from outside)
    public static final String KEY_EMAIL = "email";
   
    // Constructor
    public SessionManager(Context context){
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }
   
    /**
     * Create login session
     * */
    public void createLoginSession(String name, String email){
        // Storing login value as TRUE
        editor.putBoolean(IS_LOGIN, true);
       
        // Storing name in pref
        editor.putString(KEY_NAME, name);
       
        // Storing email in pref
        editor.putString(KEY_EMAIL, email);
       
        // commit changes
        editor.commit();
    }   

    /**
     * Get stored session data
     * */
    public HashMap<String, String> getUserDetails(){
        HashMap<String, String> user = new HashMap<String, String>();
        // user name
        user.put(KEY_NAME, pref.getString(KEY_NAME, null));
       
        // user email id
        user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
       
        // return user
        return user;
    }
   
    /**
     * Clear session details
     * */
    public void logoutUser(){
        // Clearing all data from Shared Preferences
        editor.clear();
        editor.commit();

    }
   
    /**
     * Quick check for login
     * **/
    // Get Login State
    public boolean isLoggedIn(){
        return pref.getBoolean(IS_LOGIN, false);
    }
}

How to Create Session....

01) create session object :-

SessionManager session;

02) session = new SessionManager(getApplicationContext());

03) session.createLoginSession("username","admin" );

How To Access Session Values:- 

01) create session object :-

 SessionManager session;

02)  session = new SessionManager(getApplicationContext());

03) HashMap<String, String> user = session.getUserDetails();

04) username =user.get(SessionManager.KEY_NAME);

Wednesday, December 17, 2014


 Service1.svc.cs


        public string CompanyintrestedStudentList(string companyname)
        {
            string data = "";
            DataSet ds = new DataSet();


            try
            {

                ds = SqlHelper.ExecuteDataset("Fetch_intrestedstudentlist", companyname);
                if (ds != null)
                {
                    if (ds.Tables.Count > 0)
                    {
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                                {
                                    data += (ds.Tables[0].Rows[i][j].ToString())+",";

                                }
                                data += ";";
                            }

                        }
                        else
                        {
                            return null;
                        }
                    }
                    else
                    {
                        return null;

                    }

                }
                else
                {
                    return null;

                }


            }
            catch (Exception ex)
            {
                ErrorLog.WriteError(ex.Message);
                //ErrorLog.WriteError(ex.Message + "Error Stack" + ex.StackTrace);
                //return null;
            }


            return data;

        }

 

 

 

 

How to use & access In android 

First create object:-

WebAPIRequest web = new WebAPIRequest();
    WebUrl weburl = new WebUrl();

Call Url and  Execute :-

url = weburl .setURL() + "CompanyList";
        new get_alert_activity().execute(url);

public class get_alert_activity extends AsyncTask<String, Void, Void> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            try {
               
               

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

        }

        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub
            try {
                response = web.performGet(params[0]);
                Log.i("Response Display Extraactivity", response);

            } catch (Exception e) {
                e.getMessage();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub

            super.onPostExecute(result);
            try {
                Log.i("Test", response);
                getjsontoListviewCompanyList(response);
                datalistview dlv = new datalistview();
                lv.setAdapter(dlv);

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

    public void getjsontoListviewCompanyList(String result) {
        try {

            jsonArray = new JSONArray(result);
            for (i = 0; i <= jsonArray.length(); i += 1) {
                list.add(jsonArray.getString(i));
                lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));

-------How to Use split Function and access String data-----------------------------------

           JSONObject jobj;
            jobj=new JSONObject(result);
       
            String str1=jobj.getString("exam_get_questionsResult");
           
             str2 = str1.split(";");
             len=str2.length;
             totallen=len;
            Log.i("lengthofstring",String.valueOf( str2.length) );
            newquestion = new String[len*6];
            for(int i=0 ; i < str2.length;i++)
            {
                quetiondata = str2[i].split(",");
                for(int k=0;k<6;k++)
                {
                    newquestion[j]=quetiondata[k];
                    Log.i("Question",j + newquestion[j]);
                    j++;
                   
                }
               
            }
               
       -------End Split Function Code--------------------------------        
               
            }

        } catch (Exception e) {
            // TODO: handle exception
            Toast.makeText(getApplicationContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
            Log.i("Result Response", e.getMessage());
        }
    }

    public class datalistview extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int pos) {
            // TODO Auto-generated method stub
            return list.get(pos);
        }

        @Override
        public long getItemId(int pos) {
            // TODO Auto-generated method stub
            return pos;
        }

        @Override
        public View getView(int pos, View convertedView, ViewGroup viewgroup) {
            // TODO Auto-generated method stub
            LayoutInflater inflater = getLayoutInflater();
            inflater = LayoutInflater.from(CompanyList.this);
            convertedView = inflater.inflate(R.layout.list, null);
            TextView tv = (TextView) convertedView
                    .findViewById(R.id.branch_name);
            tv.setText(list.get(pos));
            return convertedView;
        }

    }