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

    }

Sunday, September 7, 2014

Android interview questions

Android interview questions : Interview Important question answer in Android


-------------------------------------------------------------------------------------------------------

01)  What is android?

Ans :- Android is a stack of software for mobile devices which has Operating System, middleware and some key applications. The application executes within its own process and its own instance of Dalvik Virtual Machine

02)  What is activity?

Ans:- A single screen in an application, with supporting Java code.


03)  What is intent in Android?

ans :- A class (Intent) will describes what a caller desires to do. The caller will send this intent to Android's intent resolver, which finds the most suitable activity for the intent. 

04)  What Programming languages does Android support for application development?

ans:- Android applications supports using Java Programming Language. which is coded in Java and complied using Android SDK.

05) What is a resource?

ans:- A user defined JSON, XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.


06)  What is APK format?

ans:- The APK file is compressed AndroidManifest.xml file with extension .apk, Which have application code (.dex files), resource files, and other files which is compressed into single .apk file.


07)   What are the features of Android?

ans:- 
-> Components can be reused and replaced by the application framework.

-> Optimized DVM for mobile devices

-> SQLite enables to store the data in a structured manner.

-> Supports GSM telephone and Bluetooth, WiFi, 3G and EDGE technologies

-> The development is a combination of a device emulator, debugging tools, memory profiling and plug-in for Eclipse IDE




Monday, August 4, 2014

Create a Simple Calculator In Android

 

 --------------------------------------------------------------------------------------

Note:- First Create New Android Application(Project) And After Followed Following Step's

 --------------------------------------------------------------------------------------

 Step:- 1

XML: Go To Activity_main.xml OR main.xml File And  Add Following  xml Code ....

  

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical" android:layout_width="fill_parent"

    android:layout_height="fill_parent" android:paddingTop="15dp">

    <RelativeLayout android:layout_height="wrap_content"

        android:id="@+id/relativeLayout1" android:layout_width="match_parent">

    </RelativeLayout>

    <LinearLayout android:layout_height="wrap_content"

        android:layout_width="match_parent" android:id="@+id/linearLayout1">

        <TextView android:text="Enter first values" android:id="@+id/txt1"

            android:layout_width="wrap_content" android:layout_height="wrap_content"

            android:textStyle="bold"></TextView>

        <EditText android:text="" android:id="@+id/editText1"

            android:layout_width="fill_parent" android:layout_height="wrap_content"

            android:singleLine="true"></EditText>

    </LinearLayout>

    <LinearLayout android:layout_height="wrap_content"

        android:layout_width="match_parent" android:id="@+id/linearLayout2">

        <TextView android:text="Enter second value" android:id="@+id/txt2"

            android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>

        <EditText android:text="" android:id="@+id/editText2"

            android:layout_width="fill_parent" android:layout_height="wrap_content"

            android:singleLine="true"></EditText>

    </LinearLayout>

    <LinearLayout android:layout_height="wrap_content"

        android:layout_width="match_parent" android:id="@+id/linearLayout3"

        android:padding="15dp">

        <TextView android:text="Answer = " android:id="@+id/txt3"

            android:layout_width="wrap_content" android:layout_height="wrap_content"

            android:textSize="30dp"></TextView>

        <TextView android:text="" android:id="@+id/txt4"

            android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="20dp"></TextView>

    </LinearLayout>

    <LinearLayout android:layout_height="wrap_content"

        android:layout_width="match_parent" android:id="@+id/linearLayout4"

        android:paddingTop="20dp" android:paddingLeft="55dp">

        <Button android:text="+" android:id="@+id/btn1"

            android:layout_width="wrap_content" android:layout_height="wrap_content"

            android:textSize="40dp"></Button>

        <Button android:text="-" android:id="@+id/btn2"

            android:layout_width="wrap_content" android:layout_height="wrap_content"

            android:textSize="40dp"></Button>

        <Button android:text="*" android:id="@+id/btn3"

            android:layout_width="wrap_content" android:layout_height="wrap_content"

            android:textSize="40dp"></Button>

        <Button android:layout_height="wrap_content"

            android:layout_width="wrap_content" android:text="/" android:id="@+id/btn4"

            android:textSize="40dp"></Button>

        <Button android:text="%" android:id="@+id/btn5"

            android:layout_width="wrap_content" android:layout_height="wrap_content"

            android:textSize="40dp"></Button>

    </LinearLayout>

</LinearLayout>

 

  --------------------------------------------------------------------------------------

Step:- 2

JAVA:- Go To src Folder --> Go  To Java Package --> Go To  .java  File And Write Following  java Code....

 

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class calculatertest extends Activity {
    /** Called when the activity is first created. */
   
    TextView tv1;
    EditText ed1,ed2;
    Button sum,sub,mul,div,mod;
    int v1, v2 ,ans;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ed1=(EditText)findViewById(R.id.editText1);
        ed2=(EditText)findViewById(R.id.editText2);
        tv1=(TextView)findViewById(R.id.txt4);
        sum=(Button)findViewById(R.id.btn1);
        sub=(Button)findViewById(R.id.btn2);
        mul=(Button)findViewById(R.id.btn3);
        div=(Button)findViewById(R.id.btn4);
        mod=(Button)findViewById(R.id.btn5);   
  
     
        sum.setOnClickListener(new OnClickListener() {
           
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                v1=Integer.parseInt(ed1.getText().toString().trim());
                v2=Integer.parseInt(ed2.getText().toString().trim());
                ans=v1+v2;
                tv1.setText(String.valueOf(ans).toString());
               
                }
        });
       
     sub.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                v1=Integer.parseInt(ed1.getText().toString().trim());
                v2=Integer.parseInt(ed2.getText().toString().trim());
                ans=v1-v2;
                tv1.setText(String.valueOf(ans).toString());


                        }
        });
            
        mul.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
               
                v1=Integer.parseInt(ed1.getText().toString().trim());
                v2=Integer.parseInt(ed2.getText().toString().trim());
                ans=v1*v2;
                tv1.setText(String.valueOf(ans).toString());

               
               
            }
        });
   
        div.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
               
                v1=Integer.parseInt(ed1.getText().toString().trim());
                v2=Integer.parseInt(ed2.getText().toString().trim());
                ans=v1/v2;
                tv1.setText(String.valueOf(ans).toString());

               
                        }
        });
   
        mod.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
               
                v1=Integer.parseInt(ed1.getText().toString().trim());
                v2=Integer.parseInt(ed2.getText().toString().trim());
                ans=v1%v2;
                tv1.setText(String.valueOf(ans).toString());

               
            }
        });
   
    }
}

  --------------------------------------------------------------------------------------

Step:- 3

Now Run Your Android Application(Project) and Check Your Project Output.......

 

OUTPUT:- Screen Short

 

 

 

 

 

 

 

 

 

Wednesday, July 23, 2014

How To Create Email Validation....


Create login application where you will have to validate EmailID (UserName). Till the username and password is not validated , login button should remain disabled.

--------------------------------------------------------------------------------------

Note:- First Create New Android Application(Project) And After Followed Following Step's


Step:- 1

XML: Go To Activity_main.xml File And  Add Following Code....


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F0F0F0"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="               Login Form"
        android:textAllCaps="true"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#176CEC"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/editText_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"
        android:ems="10"
        android:hint="Enter Email Id"
        android:inputType="textEmailAddress"
        android:padding="12dp" />

    <Button
        android:id="@+id/btn_signup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:background="#176CEC"
        android:text="Check Valid Email"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#fff"
        android:textStyle="bold" />

</LinearLayout>


Step:- 2

JAVA:- Go To Activity_main.java File And Write Following Code....


package com.chirag.emailvalidation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.Menu;

public class MainActivity extends Activity {
EditText emailEditText;
Button btn_click;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailEditText = (EditText) findViewById(R.id.editText_email);
btn_click=(Button)findViewById(R.id.btn_signup);
btn_click.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
final String email = emailEditText.getText().toString();
if (!isValidEmail(email))
{
emailEditText.setError("Invalid Email");
Toast.makeText(getApplicationContext(),
"Invalid Email", Toast.LENGTH_LONG).show();
btn_click.setEnabled(true);
}
else
{
//emailEditText.setError("Valid Email");
Toast.makeText(getApplicationContext(),
"Valid Email", Toast.LENGTH_LONG).show();
btn_click.setEnabled(false);
}
}
});
}
// validating email id
private boolean isValidEmail(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}



Step:- 3

Now Run Your Android Application(Project) and Check Your Email Is Validate Or Not.......


OUTPUT:- Screen Short