Monday, 13 June 2016

Login

package com.tdi.rk;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;

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

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

public class Login extends AppCompatActivity implements View.OnTouchListener {

    EditText lo_mail,lo_pass;
    Button signin,btn_signup;
    TextView create;
    AQuery aQuery;
    ProgressDialog pd;
    SessionMgt sessionMgt;
    private static String deviceToken = "Empty";
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        sessionMgt = new SessionMgt(getApplicationContext());
        if((Boolean)SP.get(getApplicationContext(), AppConstants.PRE_LOGIN_IS_LOGIN, false)){
            startActivity(new Intent(getApplicationContext(),MainActivity.class));
        }

        Intent intent = getIntent();
        deviceToken = intent.getStringExtra("deviceToken");


            mRegistrationBroadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {

                    // checking for type intent filter
                    if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
                        // gcm successfully registered
                        // now subscribe to `global` topic to receive app wide notifications
                        deviceToken = intent.getStringExtra("token");
                        Log.e("TAG", "gcm successfully registered     "+deviceToken);
                        // subscribeToGlobalTopic();

                    } else if (intent.getAction().equals(Config.SENT_TOKEN_TO_SERVER)) {
                        // gcm registration id is stored in our server's MySQL
                        Log.e("TAG", "GCM registration id is sent to our server");

                    } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                        // new push notification is received
                        // handlePushNotification(intent);
                        //Toast.makeText(getApplicationContext(),"hi",Toast.LENGTH_LONG).show();
                    }
                }
            };

            if (checkPlayServices()) {
                registerGCM();
            }







        initStuff();


    }




    private void initStuff()
    {
        lo_mail = (EditText) findViewById(R.id.et_user_mail);
        lo_pass = (EditText) findViewById(R.id.et_user_pass);

        signin = (Button) findViewById(R.id.btn_signin);
        btn_signup = (Button) findViewById(R.id.btn_signup);

        aQuery = new AQuery(this);

        pd=new ProgressDialog(this);
        pd.setMessage("Login...");


        btn_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Login.this, Signup.class));
            }
        });

        TextView tv_forgotpass = (TextView) findViewById(R.id.tv_forgot_password);

        tv_forgotpass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Login.this,ForgotPassword.class));

            }
        });


        signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //aQuery.id()
                if (isNetworkConnected()) {
                    String unm = lo_mail.getText().toString().trim();
                    String pwd = lo_pass.getText().toString().trim();

                    if (unm.equals("") && emailValidator(unm)) {

                        lo_mail.setError("Enter E-mail valid Address");
                        return;
                    }
                    if (pwd.equals("")) {
                        lo_pass.setError("Enter Password");
                        return;
                    }
                    islogin(unm, pwd);
                    sessionMgt.createLoginSession(unm, pwd);
                    //finish();

                } else {
                    Toast.makeText(getApplicationContext(), "Please check Internet connection is activate to login", Toast.LENGTH_LONG).show();
                }

            }
        });



    }

        public boolean emailValidator(String email)
        {
            Pattern pattern;
            Matcher matcher;
            final 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.compile(EMAIL_PATTERN);
            matcher = pattern.matcher(email);
            return matcher.matches();
        }
    public void islogin(String usr,String pwd)
    {
           String url=AppConstants.MAIN_URL+"Login.php?email="+usr+"&pass="+pwd+"&deviceToken="+deviceToken+"&key="+AppConstants.KEY;
       // Login.php?email=b@b.com&pass=12345&deviceToken=11&key=5a14ec5b310164f2dfe49e86b06124a
            Log.d("url", "" + url);
            aQuery.progress(pd).ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {

                @Override
                public void callback(String url, JSONObject object, AjaxStatus status) {

                    if (object != null) {
                       // String data = object.optString("data");
                       // String msg = object.optString("msg");

                        try {

                            JSONObject mainJsonObject = new JSONObject(object.toString());
                            Log.d("JSON RESPONSE",""+mainJsonObject);
                            if(mainJsonObject != null){
                                if (mainJsonObject.getString("data").equals("error")){
                                    Log.d("Key",""+mainJsonObject.getString("data"));
                                    Toast.makeText(getApplicationContext(),mainJsonObject.getString("msg"),Toast.LENGTH_LONG).show();
                                }
                                else {
                                    JSONObject subJsonObject = mainJsonObject.getJSONObject("user_data");
                                    SP.put(getApplicationContext(), AppConstants.PRE_LOGIN_IS_LOGIN, true);
                                    SP.put(getApplicationContext(), AppConstants.PRE_LOGIN_USER_ID, subJsonObject.optString("userID"));
                                    SP.put(getApplicationContext(), AppConstants.PRE_LOGIN_NAME, subJsonObject.optString("name"));
                                    SP.put(getApplicationContext(), AppConstants.PRE_LOGIN_EMAIL, subJsonObject.optString("email"));
                                    SP.put(getApplicationContext(), AppConstants.PRE_LOGIN_MOBILE_NO, subJsonObject.optString("mobile"));
                                    SP.put(getApplicationContext(), AppConstants.PRE_LOGIN_COMPANY, subJsonObject.optString("company"));
                                    SP.put(getApplicationContext(), AppConstants.PRE_LOGIN_USER_PRO_PIC, subJsonObject.optString("proPic"));
                                    Log.d("image pic",subJsonObject.optString("proPic"));
                                    Toast.makeText(getApplicationContext(),mainJsonObject.getString("msg"),Toast.LENGTH_LONG).show();

                                    Intent i = new Intent(Login.this, MainActivity.class);
                                    startActivity(i);
                                }


                            }else {
                                Toast.makeText(getApplicationContext(),
                                        mainJsonObject.get("msg").toString(), Toast.LENGTH_LONG)
                                        .show();

                            }

                          /*  JSONObject userdata = object.getJSONObject("user_data");
                            String userid = userdata.optString("userID");
                            String email = userdata.optString("email");
                            String proPic = userdata.optString("proPic");
                            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();





                            startActivity(new Intent(Login.this,MainActivity.class));

                            finish();*/
                        } catch (JSONException e) {

                        }

                    } else {
                        Toast.makeText(getApplicationContext(), "Error:" + status.getCode(), Toast.LENGTH_LONG).show();
                    }

                }
            });
    }

    @Override
    public void onBackPressed() {

        AlertDialog.Builder al = new AlertDialog.Builder(this);
        al.setMessage("Are You sure Want to exit Application ?");
        al.setTitle("Exit");
        al.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent i = new Intent(Intent.ACTION_MAIN);
                i.addCategory(Intent.CATEGORY_HOME);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }
        });
        al.setNegativeButton("Cancle", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        al.show();

    }

    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        startActivity(new Intent(Login.this,Signup.class));
        return true;
    }

    private void registerGCM() {
        Intent intent = new Intent(this, GcmIntentService.class);
        intent.putExtra("key", "register");
        startService(intent);
    }
    private boolean checkPlayServices() {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
                        .show();
            } else {
                Log.i("TAG", "This device is not supported. Google Play Services not installed!");
                Toast.makeText(getApplicationContext(), "This device is not supported. Google Play Services not installed!", Toast.LENGTH_LONG).show();
                finish();
            }
            return false;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.PUSH_NOTIFICATION));

        // clearing the notification tray

    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }

}

No comments:

Post a Comment