Friday 22 January 2016

Login Example with JSON web service Android


For integrating JSON service example you need below jar for that
1. apache-mime4j-0.6.jar
2. gson-2.1.jar
3. httpmime-4.0.1,jar
4. json_simple-1.1.jar

layout_login.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:local="http://schemas.android.com/tools">

    <!--<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        local:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize" />-->


    <RelativeLayout
        android:id="@+id/rel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">

        <TextView
            android:id="@+id/txt_title"
            style="@style/LargeTextView"
            android:layout_marginBottom="@dimen/margin_15dp"
            android:layout_centerHorizontal="true"
            android:hint="Sign IN" />
        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_email"
            android:layout_width="match_parent"
            android:layout_below="@+id/txt_title"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_10dp">

            <EditText
                android:id="@+id/edt_email"
                style="@style/Edittext"
                android:hint="Email" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_pass"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/input_layout_email">

            <EditText
                android:id="@+id/edt_password"
                style="@style/Edittext"
                android:hint="Password"
                android:inputType="textPassword" />

        </android.support.design.widget.TextInputLayout>

        <TextView
            android:id="@+id/txt_forgot_password"
            style="@style/NormalTextView"
            android:layout_below="@+id/input_layout_pass"
            android:layout_marginLeft="@dimen/margin_10dp"
            android:layout_marginTop="@dimen/margin_10dp"
            android:text="@string/forgot_password" />

        <TextView
            android:id="@+id/txt_new_user"
            style="@style/NormalTextView"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/input_layout_pass"
            android:layout_marginLeft="@dimen/margin_10dp"
            android:layout_marginRight="@dimen/margin_10dp"
            android:layout_marginTop="@dimen/margin_10dp"
            android:text="@string/new_user" />

        <TextView
            android:id="@+id/txt_login"
            style="@style/NormalTextView"
            android:layout_below="@+id/txt_forgot_password"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="@dimen/margin_20dp"
            android:background="@drawable/login_rect"
            android:padding="@dimen/margin_10dp"
            android:text="LOGIN"
            android:textColor="@android:color/white" />

    </RelativeLayout>

</RelativeLayout>

LoginActivity.java

package com.example.sphere65.loginregisterskeleton;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import parser.GetSecrateKey;

public class LoginActivity extends AppCompatActivity {

    TextInputLayout mTextInputLayoutEmail;
    EditText mEditTextEmail;

    TextInputLayout mTextInputLayoutPassword;
    EditText mEditTextPassword;

    TextView mTextViewForgotPassword;
    TextView mTextViewNewUser;
    TextView mTextViewLogin;

    Context context;
    String evalue="";
    GetSecrateKey mGetSecrateKey;
    PostParseGet mPostParseGet;
    AllMethods mAllMethods;
    ProgressDialog mProgressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_login);
        context=this;
        mGetSecrateKey=new GetSecrateKey();
        mPostParseGet=new PostParseGet(LoginActivity.this);
        mAllMethods=new AllMethods(LoginActivity.this);
        mTextInputLayoutEmail=(TextInputLayout)findViewById(R.id.input_layout_email);
        mTextInputLayoutPassword=(TextInputLayout)findViewById(R.id.input_layout_pass);
        mEditTextEmail=(EditText)findViewById(R.id.edt_email);
        mEditTextPassword=(EditText)findViewById(R.id.edt_password);
        mTextViewForgotPassword=(TextView)findViewById(R.id.txt_forgot_password);
        mTextViewNewUser=(TextView)findViewById(R.id.txt_new_user);
        mTextViewLogin=(TextView)findViewById(R.id.txt_login);

        mEditTextEmail.addTextChangedListener(new MyTextWatcher(mEditTextEmail));
        mEditTextPassword.addTextChangedListener(new MyTextWatcher(mEditTextPassword));
        mTextViewLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginDone();

            }
        });
         

         

    }

    

    private void loginDone() {


        if (!validateEmail()) {
            return;
        }

       else if (!validatePassword()) {
            return;
        }
        else
        {
            Toast.makeText(getApplicationContext(), "You have logged in successfully.", Toast.LENGTH_SHORT).show();

            /* Call Login web service with neccessory parameter
            if (mAllMethods.check_Internet()==true)
            {
                new loginAysnTask().execute();
            }
            else
            {
                mAllMethods.ShowDialog(LoginActivity.this,"",getString(R.string.net_not_available),"OK");
            }
            */
            clearAllField();
        }

    }

    public class loginAysnTask extends AsyncTask<Void,Void,Void>    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog=ProgressDialog.show(LoginActivity.this,"","Loading..");
        }

        @Override
        protected Void doInBackground(Void... voids) {
            mGetSecrateKey=(GetSecrateKey)mPostParseGet.login(mGetSecrateKey,mEditTextEmail.getText().toString(),mEditTextPassword.getText().toString());
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (mProgressDialog!=null)
            {
                mProgressDialog.dismiss();
            }
            if(mPostParseGet.isNetError){
                mAllMethods.ShowDialog(LoginActivity.this, "", getString(R.string.net_not_available), "OK");
            }
            else if (mPostParseGet.isOtherError) {
                mAllMethods.ShowDialog(LoginActivity.this, "", getString(R.string.data_not_found), "OK");
            }
            else
            {
                if (mGetSecrateKey!=null)
                {
                    if (mGetSecrateKey.getRes_code().equalsIgnoreCase("1"))
                    {
                        Toast.makeText(getApplicationContext(), mGetSecrateKey.getRes_msg(), Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(), mGetSecrateKey.getRes_msg(), Toast.LENGTH_SHORT).show();

                    }

                }
            }

        }
    }
    public void clearAllField()
    {

        mEditTextEmail.clearFocus();
        mEditTextPassword.clearFocus();
     }
    private boolean validateEmail() {
        String email = mEditTextEmail.getText().toString().trim();

        if (email.isEmpty() || !isValidEmail(email)) {
            mTextInputLayoutEmail.setError(getString(R.string.err_msg_email));
            requestFocus(mEditTextEmail);
            return false;
        } else {
            mTextInputLayoutEmail.setErrorEnabled(false);
        }

        return true;
    }

    private boolean validatePassword() {
        if (mEditTextPassword.getText().toString().trim().isEmpty()) {
            mTextInputLayoutPassword.setError(getString(R.string.err_msg_password));
            requestFocus(mEditTextPassword);
            return false;
        } else {
            mTextInputLayoutPassword.setErrorEnabled(false);
        }

        return true;
    }

    private static boolean isValidEmail(String email) {
        return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
    private class MyTextWatcher implements TextWatcher {

        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void afterTextChanged(Editable editable) {
            switch (view.getId()) {

                case R.id.edt_email:
                    validateEmail();
                    break;
                case R.id.edt_password:
                    validatePassword();
                    break;
            }
        }
    }
}

AllUrl.java

public class AllUrl {

     public static String url="https://www.mylink.com/webservice/";

}

AllMethods.java

package com.example.sphere65.loginregisterskeleton;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AllMethods {
ConnectivityManager mConnectivityManager;
NetworkInfo mNetworkInfo;
boolean isNetError;
public Activity mActivity;
Context mContext;
FragmentActivity mActivity2;
Dialog mDialogRentRimDialog;


public     String formatPhoneNumber(String number){
number  =   number.substring(0, number.length()-4) + "-" + number.substring(number.length()-4, number.length());
number  =   number.substring(0,number.length()-8)+")"+number.substring(number.length()-8,number.length());
number  =   number.substring(0, number.length()-12)+"("+number.substring(number.length()-12, number.length());
number  =   number.substring(0, number.length()-14)+"+"+number.substring(number.length()-14, number.length());

return number;
}


 
 
 
public   void hideSoftKeyboard(Activity activity) {
   InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
   inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public AllMethods() {
// TODO Auto-generated constructor stub

}
public AllMethods(Context mContext) {
// TODO Auto-generated constructor stub
this.mContext=mContext;

}
public AllMethods(Activity mContext) {
// TODO Auto-generated constructor stub
this.mActivity=mContext;

}
public AllMethods(FragmentActivity mContext) {
// TODO Auto-generated constructor stub
this.mActivity=mContext;


}
 
public void ShowDialog(final Activity activity, String Title ,String Message,String Ok) 
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle(Title);
alertDialogBuilder
.setMessage(Message)
.setCancelable(true)
.setPositiveButton(Ok,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
 });
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

}




public   void hideKeyboard(Activity  mActivity2,View view) {
        InputMethodManager inputMethodManager =(InputMethodManager)mActivity2.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
public void ShowDialog(FragmentActivity activity, String Title ,String Message,String Ok)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle(Title);
alertDialogBuilder
.setMessage(Message)
.setCancelable(true)
.setPositiveButton(Ok,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
 });
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

}
/*public   boolean checkEmail(String EdittextString) {
return FragmentDashboard.emailPattern.matcher(EdittextString).matches();
}*/
public boolean check_Internet()
{
mConnectivityManager= (ConnectivityManager)mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

if(mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
{
isNetError = false;
return true;
}
else
{
isNetError = true;
return false;
}
}
 
}

PostParseGet.java


package com.example.sphere65.loginregisterskeleton;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.FragmentActivity;

import com.google.gson.Gson;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
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.apache.http.util.EntityUtils;

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

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;

import parser.GetSecrateKey;

public class PostParseGet {

public Activity mContext;
public boolean isNetError = false;
public boolean isOtherError = false;
public boolean isDeviceToken = false;
List<NameValuePair> nameValuePairs;
Object mFillObject;

public static ArrayList<String>mflist;
ConnectivityManager mConnectivityManager;
NetworkInfo mNetworkInfo;

Gson mGson;

public PostParseGet(Activity context) {
mContext = context;
mGson = new Gson();
mflist=new ArrayList<String>();
}
public PostParseGet(FragmentActivity context) {
mContext = context;
mGson = new Gson();
mflist=new ArrayList<String>();
}

public Object getmFillObject() {
return mFillObject;
}

public void setmFillObject(Object mFillObject) {
this.mFillObject = mFillObject;
}

public boolean isDeviceToken() {
return isDeviceToken;
}

public void setDeviceToken(boolean isDeviceToken) {
this.isDeviceToken = isDeviceToken;
}

/**
* Function checks internet if avail, Post data to particular Url and filled
* json object relating to the response.
* @param string
* @param nameValuePairs
* @param object
* @param context
* @return object
* @throws CustomException
* */
public Object postHttpURL(String url, List<NameValuePair> nameValuePairs, Object mObject) {
HttpPost httppost;
HttpParams httpParameters;
int timeoutConnection = 60000;
HttpClient httpclient = null;
HttpResponse response = null;
String data = "";
isOtherError = false;

System.out.println("Url " + url);
mFillObject= null;

if(check_Internet())
{
try {
mFillObject = mObject.getClass().newInstance();
HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

DefaultHttpClient client = new DefaultHttpClient();

SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
//  HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
httppost = new HttpPost(url);
httpParameters = new BasicHttpParams();
// HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
httpclient = new DefaultHttpClient(httpParameters);


MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
System.out.println("nameValuePairs "+nameValuePairs.size());
if (nameValuePairs != null)
{
for(int index=0; index < nameValuePairs.size(); index++)
{
String paramName=nameValuePairs.get(index).getName();
String paramValue=nameValuePairs.get(index).getValue();
System.out.println("paramName "+paramName);
System.out.println("paramValue "+paramValue);

if(paramName.equalsIgnoreCase("docsimage")||paramName.equalsIgnoreCase("faceimage") )
{
 
if(paramValue.length()>0)
{
   
entity.addPart(paramName, new FileBody(new File (paramValue)));

 

}
else
{
// mflist.clear();
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));

}
}
httppost.setEntity(entity);
}


response = httpclient.execute(httppost);
System.out.println("httppost " + httppost.toString());
data = EntityUtils.toString(response.getEntity());

System.out.println("Final Data "+data);
if(data.equalsIgnoreCase("{\"is_device_deleted\":true}"))
setDeviceToken(true);

mFillObject = mGson.fromJson(data, mFillObject.getClass());


} catch (Exception e) {

isOtherError = true;
e.printStackTrace();
}
}
return mFillObject;
}

/**
* Function
* Takes and keeps a reference of the passed context in order to Check whether Internet is available or not.
* @param context
* @return The return will be true if the internet is available and false if not.
*/
public boolean check_Internet()
{
mConnectivityManager= (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

if(mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
{
isNetError = false;
return true;
}
else
{
isNetError = true;
return false;
}
}


public Object login( GetSecrateKey mGetFlag,String usenrname,String password ) {

nameValuePairs = new ArrayList<NameValuePair>();
  nameValuePairs.add(new BasicNameValuePair("user_email", usenrname));
nameValuePairs.add(new BasicNameValuePair("user_password", password));

return  postHttpURL(AllUrl.url+"user/login",nameValuePairs, mGetFlag);
  }

 

}

No comments:

Post a Comment